libcoap 4.3.5
Loading...
Searching...
No Matches
coap_net.c
Go to the documentation of this file.
1/* coap_net.c -- CoAP context inteface
2 *
3 * Copyright (C) 2010--2025 Olaf Bergmann <bergmann@tzi.org> and others
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
15
18
19#include <ctype.h>
20#include <stdio.h>
21#ifdef HAVE_LIMITS_H
22#include <limits.h>
23#endif
24#ifdef HAVE_UNISTD_H
25#include <unistd.h>
26#else
27#ifdef HAVE_SYS_UNISTD_H
28#include <sys/unistd.h>
29#endif
30#endif
31#ifdef HAVE_SYS_TYPES_H
32#include <sys/types.h>
33#endif
34#ifdef HAVE_SYS_SOCKET_H
35#include <sys/socket.h>
36#endif
37#ifdef HAVE_SYS_IOCTL_H
38#include <sys/ioctl.h>
39#endif
40#ifdef HAVE_NETINET_IN_H
41#include <netinet/in.h>
42#endif
43#ifdef HAVE_ARPA_INET_H
44#include <arpa/inet.h>
45#endif
46#ifdef HAVE_NET_IF_H
47#include <net/if.h>
48#endif
49#ifdef COAP_EPOLL_SUPPORT
50#include <sys/epoll.h>
51#include <sys/timerfd.h>
52#endif /* COAP_EPOLL_SUPPORT */
53#ifdef HAVE_WS2TCPIP_H
54#include <ws2tcpip.h>
55#endif
56
57#ifdef HAVE_NETDB_H
58#include <netdb.h>
59#endif
60
61#ifdef WITH_LWIP
62#include <lwip/pbuf.h>
63#include <lwip/udp.h>
64#include <lwip/timeouts.h>
65#include <lwip/tcpip.h>
66#endif
67
68#ifndef INET6_ADDRSTRLEN
69#define INET6_ADDRSTRLEN 40
70#endif
71
72#ifndef min
73#define min(a,b) ((a) < (b) ? (a) : (b))
74#endif
75
80#define FRAC_BITS 6
81
86#define MAX_BITS 8
87
88#if FRAC_BITS > 8
89#error FRAC_BITS must be less or equal 8
90#endif
91
93#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
94 ((1 << (frac)) * fval.fractional_part + 500)/1000))
95
97#define ACK_RANDOM_FACTOR \
98 Q(FRAC_BITS, session->ack_random_factor)
99
101#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
102
103#ifndef WITH_LWIP
104
109
114#else /* !WITH_LWIP */
115
116#include <lwip/memp.h>
117
120 return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
121}
122
125 memp_free(MEMP_COAP_NODE, node);
126}
127#endif /* WITH_LWIP */
128
129unsigned int
131 unsigned int result = 0;
132 coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
133
134 if (ctx->sendqueue) {
135 /* delta < 0 means that the new time stamp is before the old. */
136 if (delta <= 0) {
137 ctx->sendqueue->t -= delta;
138 } else {
139 /* This case is more complex: The time must be advanced forward,
140 * thus possibly leading to timed out elements at the queue's
141 * start. For every element that has timed out, its relative
142 * time is set to zero and the result counter is increased. */
143
144 coap_queue_t *q = ctx->sendqueue;
145 coap_tick_t t = 0;
146 while (q && (t + q->t < (coap_tick_t)delta)) {
147 t += q->t;
148 q->t = 0;
149 result++;
150 q = q->next;
151 }
152
153 /* finally adjust the first element that has not expired */
154 if (q) {
155 q->t = (coap_tick_t)delta - t;
156 }
157 }
158 }
159
160 /* adjust basetime */
161 ctx->sendqueue_basetime += delta;
162
163 return result;
164}
165
166int
168 coap_queue_t *p, *q;
169 if (!queue || !node)
170 return 0;
171
172 /* set queue head if empty */
173 if (!*queue) {
174 *queue = node;
175 return 1;
176 }
177
178 /* replace queue head if PDU's time is less than head's time */
179 q = *queue;
180 if (node->t < q->t) {
181 node->next = q;
182 *queue = node;
183 q->t -= node->t; /* make q->t relative to node->t */
184 return 1;
185 }
186
187 /* search for right place to insert */
188 do {
189 node->t -= q->t; /* make node-> relative to q->t */
190 p = q;
191 q = q->next;
192 } while (q && q->t <= node->t);
193
194 /* insert new item */
195 if (q) {
196 q->t -= node->t; /* make q->t relative to node->t */
197 }
198 node->next = q;
199 p->next = node;
200 return 1;
201}
202
203COAP_API int
205 int ret;
206#if COAP_THREAD_SAFE
207 coap_context_t *context;
208#endif /* COAP_THREAD_SAFE */
209
210 if (!node)
211 return 0;
212 if (!node->session)
213 return coap_delete_node_lkd(node);
214
215#if COAP_THREAD_SAFE
216 /* Keep copy as node will be going away */
217 context = node->session->context;
218 (void)context;
219#endif /* COAP_THREAD_SAFE */
220 coap_lock_lock(context, return 0);
221 ret = coap_delete_node_lkd(node);
222 coap_lock_unlock(context);
223 return ret;
224}
225
226int
228 if (!node)
229 return 0;
230
232 if (node->session) {
233 /*
234 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
235 */
236 if (node->session->context->sendqueue) {
237 LL_DELETE(node->session->context->sendqueue, node);
238 }
240 }
241 coap_free_node(node);
242
243 return 1;
244}
245
246void
248 if (!queue)
249 return;
250
251 coap_delete_all(queue->next);
253}
254
257 coap_queue_t *node;
258 node = coap_malloc_node();
259
260 if (!node) {
261 coap_log_warn("coap_new_node: malloc failed\n");
262 return NULL;
263 }
264
265 memset(node, 0, sizeof(*node));
266 return node;
267}
268
271 if (!context || !context->sendqueue)
272 return NULL;
273
274 return context->sendqueue;
275}
276
279 coap_queue_t *next;
280
281 if (!context || !context->sendqueue)
282 return NULL;
283
284 next = context->sendqueue;
285 context->sendqueue = context->sendqueue->next;
286 if (context->sendqueue) {
287 context->sendqueue->t += next->t;
288 }
289 next->next = NULL;
290 return next;
291}
292
293#if COAP_CLIENT_SUPPORT
294const coap_bin_const_t *
296
297 if (session->psk_key) {
298 return session->psk_key;
299 }
300 if (session->cpsk_setup_data.psk_info.key.length)
301 return &session->cpsk_setup_data.psk_info.key;
302
303 /* Not defined in coap_new_client_session_psk2() */
304 return NULL;
305}
306
307const coap_bin_const_t *
309
310 if (session->psk_identity) {
311 return session->psk_identity;
312 }
314 return &session->cpsk_setup_data.psk_info.identity;
315
316 /* Not defined in coap_new_client_session_psk2() */
317 return NULL;
318}
319#endif /* COAP_CLIENT_SUPPORT */
320
321#if COAP_SERVER_SUPPORT
322const coap_bin_const_t *
324
325 if (session->psk_key)
326 return session->psk_key;
327
329 return &session->context->spsk_setup_data.psk_info.key;
330
331 /* Not defined in coap_context_set_psk2() */
332 return NULL;
333}
334
335const coap_bin_const_t *
337
338 if (session->psk_hint)
339 return session->psk_hint;
340
342 return &session->context->spsk_setup_data.psk_info.hint;
343
344 /* Not defined in coap_context_set_psk2() */
345 return NULL;
346}
347
348COAP_API int
350 const char *hint,
351 const uint8_t *key,
352 size_t key_len) {
353 int ret;
354
355 coap_lock_lock(ctx, return 0);
356 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
357 coap_lock_unlock(ctx);
358 return ret;
359}
360
361int
363 const char *hint,
364 const uint8_t *key,
365 size_t key_len) {
366 coap_dtls_spsk_t setup_data;
367
369 memset(&setup_data, 0, sizeof(setup_data));
370 if (hint) {
371 setup_data.psk_info.hint.s = (const uint8_t *)hint;
372 setup_data.psk_info.hint.length = strlen(hint);
373 }
374
375 if (key && key_len > 0) {
376 setup_data.psk_info.key.s = key;
377 setup_data.psk_info.key.length = key_len;
378 }
379
380 return coap_context_set_psk2_lkd(ctx, &setup_data);
381}
382
383COAP_API int
385 int ret;
386
387 coap_lock_lock(ctx, return 0);
388 ret = coap_context_set_psk2_lkd(ctx, setup_data);
389 coap_lock_unlock(ctx);
390 return ret;
391}
392
393int
395 if (!setup_data)
396 return 0;
397
399 ctx->spsk_setup_data = *setup_data;
400
402 return coap_dtls_context_set_spsk(ctx, setup_data);
403 }
404 return 0;
405}
406
407COAP_API int
409 const coap_dtls_pki_t *setup_data) {
410 int ret;
411
412 coap_lock_lock(ctx, return 0);
413 ret = coap_context_set_pki_lkd(ctx, setup_data);
414 coap_lock_unlock(ctx);
415 return ret;
416}
417
418int
420 const coap_dtls_pki_t *setup_data) {
422 if (!setup_data)
423 return 0;
424 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
425 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
426 return 0;
427 }
429 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
430 }
431 return 0;
432}
433#endif /* ! COAP_SERVER_SUPPORT */
434
435COAP_API int
437 const char *ca_file,
438 const char *ca_dir) {
439 int ret;
440
441 coap_lock_lock(ctx, return 0);
442 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
443 coap_lock_unlock(ctx);
444 return ret;
445}
446
447int
449 const char *ca_file,
450 const char *ca_dir) {
452 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
453 }
454 return 0;
455}
456
457void
458coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
459 context->ping_timeout = seconds;
460}
461
462int
464#if COAP_CLIENT_SUPPORT
465 return coap_dtls_set_cid_tuple_change(context, every);
466#else /* ! COAP_CLIENT_SUPPORT */
467 (void)context;
468 (void)every;
469 return 0;
470#endif /* ! COAP_CLIENT_SUPPORT */
471}
472
473void
475 size_t max_token_size) {
476 assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
477 max_token_size <= COAP_TOKEN_EXT_MAX);
478 context->max_token_size = (uint32_t)max_token_size;
479}
480
481void
483 unsigned int max_idle_sessions) {
484 context->max_idle_sessions = max_idle_sessions;
485}
486
487unsigned int
489 return context->max_idle_sessions;
490}
491
492void
494 unsigned int max_handshake_sessions) {
495 context->max_handshake_sessions = max_handshake_sessions;
496}
497
498unsigned int
502
503static unsigned int s_csm_timeout = 30;
504
505void
507 unsigned int csm_timeout) {
508 s_csm_timeout = csm_timeout;
509 coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
510}
511
512unsigned int
514 (void)context;
515 return s_csm_timeout;
516}
517
518void
520 unsigned int csm_timeout_ms) {
521 if (csm_timeout_ms < 10)
522 csm_timeout_ms = 10;
523 if (csm_timeout_ms > 10000)
524 csm_timeout_ms = 10000;
525 context->csm_timeout_ms = csm_timeout_ms;
526}
527
528unsigned int
530 return context->csm_timeout_ms;
531}
532
533void
535 uint32_t csm_max_message_size) {
536 assert(csm_max_message_size >= 64);
537 context->csm_max_message_size = csm_max_message_size;
538}
539
540uint32_t
544
545void
547 unsigned int session_timeout) {
548 context->session_timeout = session_timeout;
549}
550
551unsigned int
553 return context->session_timeout;
554}
555
556int
558#ifdef COAP_EPOLL_SUPPORT
559 return context->epfd;
560#else /* ! COAP_EPOLL_SUPPORT */
561 (void)context;
562 return -1;
563#endif /* ! COAP_EPOLL_SUPPORT */
564}
565
566int
568#ifdef COAP_EPOLL_SUPPORT
569 return 1;
570#else /* ! COAP_EPOLL_SUPPORT */
571 return 0;
572#endif /* ! COAP_EPOLL_SUPPORT */
573}
574
575int
577#ifdef COAP_THREAD_SAFE
578 return 1;
579#else /* ! COAP_THREAD_SAFE */
580 return 0;
581#endif /* ! COAP_THREAD_SAFE */
582}
583
584int
586#ifdef COAP_IPV4_SUPPORT
587 return 1;
588#else /* ! COAP_IPV4_SUPPORT */
589 return 0;
590#endif /* ! COAP_IPV4_SUPPORT */
591}
592
593int
595#ifdef COAP_IPV6_SUPPORT
596 return 1;
597#else /* ! COAP_IPV6_SUPPORT */
598 return 0;
599#endif /* ! COAP_IPV6_SUPPORT */
600}
601
602int
604#ifdef COAP_CLIENT_SUPPORT
605 return 1;
606#else /* ! COAP_CLIENT_SUPPORT */
607 return 0;
608#endif /* ! COAP_CLIENT_SUPPORT */
609}
610
611int
613#ifdef COAP_SERVER_SUPPORT
614 return 1;
615#else /* ! COAP_SERVER_SUPPORT */
616 return 0;
617#endif /* ! COAP_SERVER_SUPPORT */
618}
619
620int
622#ifdef COAP_AF_UNIX_SUPPORT
623 return 1;
624#else /* ! COAP_AF_UNIX_SUPPORT */
625 return 0;
626#endif /* ! COAP_AF_UNIX_SUPPORT */
627}
628
629void
630coap_context_set_app_data(coap_context_t *context, void *app_data) {
631 assert(context);
632 context->app = app_data;
633}
634
635void *
637 assert(context);
638 return context->app;
639}
640
642coap_new_context(const coap_address_t *listen_addr) {
644
645#if ! COAP_SERVER_SUPPORT
646 (void)listen_addr;
647#endif /* COAP_SERVER_SUPPORT */
648
649 if (!coap_started) {
650 coap_startup();
651 coap_log_warn("coap_startup() should be called before any other "
652 "coap_*() functions are called\n");
653 }
654
656 if (!c) {
657 coap_log_emerg("coap_init: malloc: failed\n");
658 return NULL;
659 }
660 memset(c, 0, sizeof(coap_context_t));
661
662 coap_lock_lock(c, coap_free_type(COAP_CONTEXT, c); return NULL);
663#ifdef COAP_EPOLL_SUPPORT
664 c->epfd = epoll_create1(0);
665 if (c->epfd == -1) {
666 coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
668 errno);
669 goto onerror;
670 }
671 if (c->epfd != -1) {
672 c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
673 if (c->eptimerfd == -1) {
674 coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
676 errno);
677 goto onerror;
678 } else {
679 int ret;
680 struct epoll_event event;
681
682 /* Needed if running 32bit as ptr is only 32bit */
683 memset(&event, 0, sizeof(event));
684 event.events = EPOLLIN;
685 /* We special case this event by setting to NULL */
686 event.data.ptr = NULL;
687
688 ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
689 if (ret == -1) {
690 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
691 "coap_new_context",
692 coap_socket_strerror(), errno);
693 goto onerror;
694 }
695 }
696 }
697#endif /* COAP_EPOLL_SUPPORT */
698
701 if (!c->dtls_context) {
702 coap_log_emerg("coap_init: no DTLS context available\n");
704 return NULL;
705 }
706 }
707
708 /* set default CSM values */
709 c->csm_timeout_ms = 1000;
710 c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
711
712#if COAP_SERVER_SUPPORT
713 if (listen_addr) {
714 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
715 if (endpoint == NULL) {
716 goto onerror;
717 }
718 }
719#endif /* COAP_SERVER_SUPPORT */
720
721 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
722
724 return c;
725
726#if defined(COAP_EPOLL_SUPPORT) || COAP_SERVER_SUPPORT
727onerror:
729 return NULL;
730#endif /* COAP_EPOLL_SUPPORT || COAP_SERVER_SUPPORT */
731}
732
733void
734coap_set_app_data(coap_context_t *ctx, void *app_data) {
735 assert(ctx);
736 ctx->app = app_data;
737}
738
739void *
741 assert(ctx);
742 return ctx->app;
743}
744
745COAP_API void
747 if (!context)
748 return;
749 coap_lock_lock(context, return);
750 coap_free_context_lkd(context);
751 coap_lock_unlock(context);
752}
753
754void
756 if (!context)
757 return;
758
759 coap_lock_check_locked(context);
760#if COAP_SERVER_SUPPORT
761 /* Removing a resource may cause a NON unsolicited observe to be sent */
763#endif /* COAP_SERVER_SUPPORT */
764
765 coap_delete_all(context->sendqueue);
766 context->sendqueue = NULL;
767
768#ifdef WITH_LWIP
769 if (context->timer_configured) {
770 LOCK_TCPIP_CORE();
771 sys_untimeout(coap_io_process_timeout, (void *)context);
772 UNLOCK_TCPIP_CORE();
773 context->timer_configured = 0;
774 }
775#endif /* WITH_LWIP */
776
777#if COAP_ASYNC_SUPPORT
778 coap_delete_all_async(context);
779#endif /* COAP_ASYNC_SUPPORT */
780
781#if COAP_OSCORE_SUPPORT
782 coap_delete_all_oscore(context);
783#endif /* COAP_OSCORE_SUPPORT */
784
785#if COAP_SERVER_SUPPORT
786 coap_cache_entry_t *cp, *ctmp;
787
788 HASH_ITER(hh, context->cache, cp, ctmp) {
789 coap_delete_cache_entry(context, cp);
790 }
791 if (context->cache_ignore_count) {
793 }
794
795 coap_endpoint_t *ep, *tmp;
796
797 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
799 }
800#endif /* COAP_SERVER_SUPPORT */
801
802#if COAP_CLIENT_SUPPORT
803 coap_session_t *sp, *rtmp;
804
805 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
807 }
808#endif /* COAP_CLIENT_SUPPORT */
809
810 if (context->dtls_context)
812#ifdef COAP_EPOLL_SUPPORT
813 if (context->eptimerfd != -1) {
814 int ret;
815 struct epoll_event event;
816
817 /* Kernels prior to 2.6.9 expect non NULL event parameter */
818 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
819 if (ret == -1) {
820 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
821 "coap_free_context",
822 coap_socket_strerror(), errno);
823 }
824 close(context->eptimerfd);
825 context->eptimerfd = -1;
826 }
827 if (context->epfd != -1) {
828 close(context->epfd);
829 context->epfd = -1;
830 }
831#endif /* COAP_EPOLL_SUPPORT */
832#if COAP_SERVER_SUPPORT
833#if COAP_WITH_OBSERVE_PERSIST
834 coap_persist_cleanup(context);
835#endif /* COAP_WITH_OBSERVE_PERSIST */
836#endif /* COAP_SERVER_SUPPORT */
837#if COAP_PROXY_SUPPORT
838 coap_proxy_cleanup(context);
839#endif /* COAP_PROXY_SUPPORT */
840
843}
844
845int
847 coap_pdu_t *pdu,
848 coap_opt_filter_t *unknown) {
849 coap_context_t *ctx = session->context;
850 coap_opt_iterator_t opt_iter;
851 int ok = 1;
852 coap_option_num_t last_number = -1;
853
855
856 while (coap_option_next(&opt_iter)) {
857 if (opt_iter.number & 0x01) {
858 /* first check the known built-in critical options */
859 switch (opt_iter.number) {
860#if COAP_Q_BLOCK_SUPPORT
863 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
864 coap_log_debug("disabled support for critical option %u\n",
865 opt_iter.number);
866 ok = 0;
867 coap_option_filter_set(unknown, opt_iter.number);
868 }
869 break;
870#endif /* COAP_Q_BLOCK_SUPPORT */
882 break;
884 /* Valid critical if doing OSCORE */
885#if COAP_OSCORE_SUPPORT
886 if (ctx->p_osc_ctx)
887 break;
888#endif /* COAP_OSCORE_SUPPORT */
889 /* Fall Through */
890 default:
891 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
892#if COAP_SERVER_SUPPORT
893 if ((opt_iter.number & 0x02) == 0) {
894 coap_opt_iterator_t t_iter;
895
896 /* Safe to forward - check if proxy pdu */
897 if (session->proxy_session)
898 break;
899 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
902 pdu->crit_opt = 1;
903 break;
904 }
905 }
906#endif /* COAP_SERVER_SUPPORT */
907 coap_log_debug("unknown critical option %d\n", opt_iter.number);
908 ok = 0;
909
910 /* When opt_iter.number cannot be set in unknown, all of the appropriate
911 * slots have been used up and no more options can be tracked.
912 * Safe to break out of this loop as ok is already set. */
913 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
914 break;
915 }
916 }
917 }
918 }
919 if (last_number == opt_iter.number) {
920 /* Check for duplicated option RFC 5272 5.4.5 */
921 if (!coap_option_check_repeatable(opt_iter.number)) {
922 ok = 0;
923 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
924 break;
925 }
926 }
927 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
928 COAP_PDU_IS_REQUEST(pdu)) {
929 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
930 coap_block_b_t block;
931
932 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
933 if (block.m) {
934 size_t used_size = pdu->used_size;
935 unsigned char buf[4];
936
937 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
938 block.m = 0;
939 coap_update_option(pdu, opt_iter.number,
940 coap_encode_var_safe(buf, sizeof(buf),
941 ((block.num << 4) |
942 (block.m << 3) |
943 block.aszx)),
944 buf);
945 if (used_size != pdu->used_size) {
946 /* Unfortunately need to restart the scan */
948 last_number = -1;
949 continue;
950 }
951 }
952 }
953 }
954 last_number = opt_iter.number;
955 }
956
957 return ok;
958}
959
961coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
962 coap_mid_t mid;
963
964 coap_lock_lock(session->context, return COAP_INVALID_MID);
965 mid = coap_send_rst_lkd(session, request);
966 coap_lock_unlock(session->context);
967 return mid;
968}
969
971coap_send_rst_lkd(coap_session_t *session, const coap_pdu_t *request) {
972 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
973}
974
976coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
977 coap_mid_t mid;
978
979 coap_lock_lock(session->context, return COAP_INVALID_MID);
980 mid = coap_send_ack_lkd(session, request);
981 coap_lock_unlock(session->context);
982 return mid;
983}
984
986coap_send_ack_lkd(coap_session_t *session, const coap_pdu_t *request) {
987 coap_pdu_t *response;
989
991 if (request && request->type == COAP_MESSAGE_CON &&
992 COAP_PROTO_NOT_RELIABLE(session->proto)) {
993 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
994 if (response)
995 result = coap_send_internal(session, response, NULL);
996 }
997 return result;
998}
999
1000ssize_t
1002 ssize_t bytes_written = -1;
1003 assert(pdu->hdr_size > 0);
1004
1005 /* Caller handles partial writes */
1006 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1007 pdu->token - pdu->hdr_size,
1008 pdu->used_size + pdu->hdr_size);
1010 return bytes_written;
1011}
1012
1013static ssize_t
1015 ssize_t bytes_written;
1016
1017 if (session->state == COAP_SESSION_STATE_NONE) {
1018#if ! COAP_CLIENT_SUPPORT
1019 return -1;
1020#else /* COAP_CLIENT_SUPPORT */
1021 if (session->type != COAP_SESSION_TYPE_CLIENT)
1022 return -1;
1023#endif /* COAP_CLIENT_SUPPORT */
1024 }
1025
1026 if (pdu->type == COAP_MESSAGE_CON &&
1027 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1028 (session->sock.flags & COAP_SOCKET_MULTICAST)) {
1029 /* Violates RFC72522 8.1 */
1030 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1031 return -1;
1032 }
1033
1034 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1035 (pdu->type == COAP_MESSAGE_CON &&
1036 session->con_active >= COAP_NSTART(session))) {
1037 return coap_session_delay_pdu(session, pdu, node);
1038 }
1039
1040 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1041 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1042 return coap_session_delay_pdu(session, pdu, node);
1043
1044 bytes_written = coap_session_send_pdu(session, pdu);
1045 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1047 session->con_active++;
1048
1049 return bytes_written;
1050}
1051
1054 const coap_pdu_t *request,
1055 coap_pdu_code_t code,
1056 coap_opt_filter_t *opts) {
1057 coap_mid_t mid;
1058
1059 coap_lock_lock(session->context, return COAP_INVALID_MID);
1060 mid = coap_send_error_lkd(session, request, code, opts);
1061 coap_lock_unlock(session->context);
1062 return mid;
1063}
1064
1067 const coap_pdu_t *request,
1068 coap_pdu_code_t code,
1069 coap_opt_filter_t *opts) {
1070 coap_pdu_t *response;
1072
1073 assert(request);
1074 assert(session);
1075
1076 response = coap_new_error_response(request, code, opts);
1077 if (response)
1078 result = coap_send_internal(session, response, NULL);
1079
1080 return result;
1081}
1082
1085 coap_pdu_type_t type) {
1086 coap_mid_t mid;
1087
1088 coap_lock_lock(session->context, return COAP_INVALID_MID);
1089 mid = coap_send_message_type_lkd(session, request, type);
1090 coap_lock_unlock(session->context);
1091 return mid;
1092}
1093
1096 coap_pdu_type_t type) {
1097 coap_pdu_t *response;
1099
1101 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1102 response = coap_pdu_init(type, 0, request->mid, 0);
1103 if (response)
1104 result = coap_send_internal(session, response, NULL);
1105 }
1106 return result;
1107}
1108
1122unsigned int
1123coap_calc_timeout(coap_session_t *session, unsigned char r) {
1124 unsigned int result;
1125
1126 /* The integer 1.0 as a Qx.FRAC_BITS */
1127#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1128
1129 /* rounds val up and right shifts by frac positions */
1130#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1131
1132 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1133 * make the result a rounded Qx.FRAC_BITS */
1134 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1135
1136 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1137 * make the result a rounded Qx.FRAC_BITS */
1138 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1139
1140 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1141 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1142 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1143
1144#undef FP1
1145#undef SHR_FP
1146}
1147
1150 coap_queue_t *node) {
1151 coap_tick_t now;
1152
1153 node->session = coap_session_reference_lkd(session);
1154
1155 /* Set timer for pdu retransmission. If this is the first element in
1156 * the retransmission queue, the base time is set to the current
1157 * time and the retransmission time is node->timeout. If there is
1158 * already an entry in the sendqueue, we must check if this node is
1159 * to be retransmitted earlier. Therefore, node->timeout is first
1160 * normalized to the base time and then inserted into the queue with
1161 * an adjusted relative time.
1162 */
1163 coap_ticks(&now);
1164 if (context->sendqueue == NULL) {
1165 node->t = node->timeout << node->retransmit_cnt;
1166 context->sendqueue_basetime = now;
1167 } else {
1168 /* make node->t relative to context->sendqueue_basetime */
1169 node->t = (now - context->sendqueue_basetime) +
1170 (node->timeout << node->retransmit_cnt);
1171 }
1172
1173 coap_insert_node(&context->sendqueue, node);
1174
1175 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1176 coap_session_str(node->session), node->id,
1177 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1179
1180 coap_update_io_timer(context, node->t);
1181
1182 return node->id;
1183}
1184
1185#if COAP_CLIENT_SUPPORT
1186/*
1187 * Sent out a test PDU for Extended Token
1188 */
1189static coap_mid_t
1190coap_send_test_extended_token(coap_session_t *session) {
1191 coap_pdu_t *pdu;
1193 size_t i;
1194 coap_binary_t *token;
1195
1196 coap_log_debug("Testing for Extended Token support\n");
1197 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1199 coap_new_message_id_lkd(session),
1201 if (!pdu)
1202 return COAP_INVALID_MID;
1203
1204 token = coap_new_binary(session->max_token_size);
1205 if (token == NULL) {
1207 return COAP_INVALID_MID;
1208 }
1209 for (i = 0; i < session->max_token_size; i++) {
1210 token->s[i] = (uint8_t)(i + 1);
1211 }
1212 coap_add_token(pdu, session->max_token_size, token->s);
1213 coap_delete_binary(token);
1214
1216
1217 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1218 if ((mid = coap_send_internal(session, pdu, NULL)) == COAP_INVALID_MID)
1219 return COAP_INVALID_MID;
1220 session->remote_test_mid = mid;
1221 return mid;
1222}
1223#endif /* COAP_CLIENT_SUPPORT */
1224
1225int
1227#if COAP_CLIENT_SUPPORT
1228 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1229 int timeout_ms = 5000;
1230 coap_session_state_t current_state = session->state;
1231
1232 if (session->delay_recursive) {
1233 return 0;
1234 } else {
1235 session->delay_recursive = 1;
1236 }
1237 /*
1238 * Need to wait for first request to get out and response back before
1239 * continuing.. Response handler has to clear doing_first if not an error.
1240 */
1242 while (session->doing_first != 0) {
1243 int result = coap_io_process_lkd(session->context, 1000);
1244
1245 if (result < 0) {
1246 session->doing_first = 0;
1247 session->delay_recursive = 0;
1248 coap_session_release_lkd(session);
1249 return 0;
1250 }
1251
1252 /* coap_io_process_lkd() may have updated session state */
1253 if (session->state == COAP_SESSION_STATE_CSM &&
1254 current_state != COAP_SESSION_STATE_CSM) {
1255 /* Update timeout and restart the clock for CSM timeout */
1256 current_state = COAP_SESSION_STATE_CSM;
1257 timeout_ms = session->context->csm_timeout_ms;
1258 result = 0;
1259 }
1260
1261 if (result < timeout_ms) {
1262 timeout_ms -= result;
1263 } else {
1264 if (session->doing_first == 1) {
1265 /* Timeout failure of some sort with first request */
1266 session->doing_first = 0;
1267 if (session->state == COAP_SESSION_STATE_CSM) {
1268 coap_log_debug("** %s: timeout waiting for CSM response\n",
1269 coap_session_str(session));
1270 session->csm_not_seen = 1;
1271 coap_session_connected(session);
1272 } else {
1273 coap_log_debug("** %s: timeout waiting for first response\n",
1274 coap_session_str(session));
1275 }
1276 }
1277 }
1278 }
1279 session->delay_recursive = 0;
1280 coap_session_release_lkd(session);
1281 }
1282#else /* ! COAP_CLIENT_SUPPORT */
1283 (void)session;
1284#endif /* ! COAP_CLIENT_SUPPORT */
1285 return 1;
1286}
1287
1288/*
1289 * return 0 Invalid
1290 * 1 Valid
1291 */
1292int
1294
1295 /* Check validity of sending code */
1296 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1297 case 0: /* Empty or request */
1298 case 2: /* Success */
1299 case 3: /* Reserved for future use */
1300 case 4: /* Client error */
1301 case 5: /* Server error */
1302 break;
1303 case 7: /* Reliable signalling */
1304 if (COAP_PROTO_RELIABLE(session->proto))
1305 break;
1306 /* Not valid if UDP */
1307 /* Fall through */
1308 case 1: /* Invalid */
1309 case 6: /* Invalid */
1310 default:
1311 return 0;
1312 }
1313 return 1;
1314}
1315
1316#if COAP_CLIENT_SUPPORT
1317/*
1318 * If type is CON and protocol is not reliable, there is no need to set up
1319 * lg_crcv if it can be built up based on sent PDU if there is a
1320 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1321 * (Q-)Block1.
1322 */
1323static int
1324coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1325 coap_opt_iterator_t opt_iter;
1326
1327 if (
1329 session->oscore_encryption ||
1330#endif /* COAP_OSCORE_SUPPORT */
1331 ((pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) &&
1333 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1335 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1336#endif /* COAP_Q_BLOCK_SUPPORT */
1337 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1338 return 1;
1339 }
1340 return 0;
1341}
1342#endif /* COAP_CLIENT_SUPPORT */
1343
1346 coap_mid_t mid;
1347
1348 coap_lock_lock(session->context, return COAP_INVALID_MID);
1349 mid = coap_send_lkd(session, pdu);
1350 coap_lock_unlock(session->context);
1351 return mid;
1352}
1353
1357#if COAP_CLIENT_SUPPORT
1358 coap_lg_crcv_t *lg_crcv = NULL;
1359 coap_opt_iterator_t opt_iter;
1360 coap_block_b_t block;
1361 int observe_action = -1;
1362 int have_block1 = 0;
1363 coap_opt_t *opt;
1364#endif /* COAP_CLIENT_SUPPORT */
1365
1366 assert(pdu);
1367
1369
1370 /* Check validity of sending code */
1371 if (!coap_check_code_class(session, pdu)) {
1372 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1374 pdu->code & 0x1f);
1375 goto error;
1376 }
1377 pdu->session = session;
1378#if COAP_CLIENT_SUPPORT
1379 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1380 !coap_netif_available(session)) {
1381 coap_log_debug("coap_send: Socket closed\n");
1382 goto error;
1383 }
1384 /*
1385 * If this is not the first client request and are waiting for a response
1386 * to the first client request, then drop sending out this next request
1387 * until all is properly established.
1388 */
1389 if (!coap_client_delay_first(session)) {
1390 goto error;
1391 }
1392
1393 /* Indicate support for Extended Tokens if appropriate */
1394 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1396 session->type == COAP_SESSION_TYPE_CLIENT &&
1397 COAP_PDU_IS_REQUEST(pdu)) {
1398 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1399 /*
1400 * When the pass / fail response for Extended Token is received, this PDU
1401 * will get transmitted.
1402 */
1403 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1404 goto error;
1405 }
1406 }
1407 /*
1408 * For reliable protocols, this will get cleared after CSM exchanged
1409 * in coap_session_connected()
1410 */
1411 session->doing_first = 1;
1412 if (!coap_client_delay_first(session)) {
1413 goto error;
1414 }
1415 }
1416
1417 /*
1418 * Check validity of token length
1419 */
1420 if (COAP_PDU_IS_REQUEST(pdu) &&
1421 pdu->actual_token.length > session->max_token_size) {
1422 coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1423 pdu->actual_token.length, session->max_token_size);
1424 goto error;
1425 }
1426
1427 /* A lot of the reliable code assumes type is CON */
1428 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1429 pdu->type = COAP_MESSAGE_CON;
1430
1431#if COAP_OSCORE_SUPPORT
1432 if (session->oscore_encryption) {
1433 if (session->recipient_ctx->initial_state == 1) {
1434 /*
1435 * Not sure if remote supports OSCORE, or is going to send us a
1436 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1437 * is OK. Continue sending current pdu to test things.
1438 */
1439 session->doing_first = 1;
1440 }
1441 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1443 goto error;
1444 }
1445 }
1446#endif /* COAP_OSCORE_SUPPORT */
1447
1448 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1449 return coap_send_internal(session, pdu, NULL);
1450 }
1451
1452 if (COAP_PDU_IS_REQUEST(pdu)) {
1453 uint8_t buf[4];
1454
1455 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1456
1457 if (opt) {
1458 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1459 coap_opt_length(opt));
1460 }
1461
1462 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1463 (block.m == 1 || block.bert == 1)) {
1464 have_block1 = 1;
1465 }
1466#if COAP_Q_BLOCK_SUPPORT
1467 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1468 (block.m == 1 || block.bert == 1)) {
1469 if (have_block1) {
1470 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1472 }
1473 have_block1 = 1;
1474 }
1475#endif /* COAP_Q_BLOCK_SUPPORT */
1476 if (observe_action != COAP_OBSERVE_CANCEL) {
1477 /* Warn about re-use of tokens */
1478 if (session->last_token &&
1479 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1480 coap_log_debug("Token reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n");
1481 }
1484 pdu->actual_token.length);
1485 } else {
1486 /* observe_action == COAP_OBSERVE_CANCEL */
1487 coap_binary_t tmp;
1488 int ret;
1489
1490 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1491 /* Unfortunately need to change the ptr type to be r/w */
1492 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1493 tmp.length = pdu->actual_token.length;
1494 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1495 if (ret == 1) {
1496 /* Observe Cancel successfully sent */
1498 return ret;
1499 }
1500 /* Some mismatch somewhere - continue to send original packet */
1501 }
1502 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1503 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1507 coap_encode_var_safe(buf, sizeof(buf),
1508 ++session->tx_rtag),
1509 buf);
1510 } else {
1511 memset(&block, 0, sizeof(block));
1512 }
1513
1514#if COAP_Q_BLOCK_SUPPORT
1515 /* Indicate support for Q-Block if appropriate */
1516 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1517 session->type == COAP_SESSION_TYPE_CLIENT &&
1518 COAP_PDU_IS_REQUEST(pdu)) {
1519 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1520 goto error;
1521 }
1522 session->doing_first = 1;
1523 if (!coap_client_delay_first(session)) {
1524 /* Q-Block test Session has failed for some reason */
1525 set_block_mode_drop_q(session->block_mode);
1526 goto error;
1527 }
1528 }
1529#endif /* COAP_Q_BLOCK_SUPPORT */
1530
1531#if COAP_Q_BLOCK_SUPPORT
1532 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1533#endif /* COAP_Q_BLOCK_SUPPORT */
1534 {
1535 /* Need to check if we need to reset Q-Block to Block */
1536 uint8_t buf[4];
1537
1538 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1541 coap_encode_var_safe(buf, sizeof(buf),
1542 (block.num << 4) | (0 << 3) | block.szx),
1543 buf);
1544 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1545 /* Need to update associated lg_xmit */
1546 coap_lg_xmit_t *lg_xmit;
1547
1548 LL_FOREACH(session->lg_xmit, lg_xmit) {
1549 if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1550 lg_xmit->b.b1.app_token &&
1551 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1552 /* Update the skeletal PDU with the block1 option */
1555 coap_encode_var_safe(buf, sizeof(buf),
1556 (block.num << 4) | (0 << 3) | block.szx),
1557 buf);
1558 break;
1559 }
1560 }
1561 }
1562 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1565 coap_encode_var_safe(buf, sizeof(buf),
1566 (block.num << 4) | (block.m << 3) | block.szx),
1567 buf);
1568 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1569 /* Need to update associated lg_xmit */
1570 coap_lg_xmit_t *lg_xmit;
1571
1572 LL_FOREACH(session->lg_xmit, lg_xmit) {
1573 if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1574 lg_xmit->b.b1.app_token &&
1575 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1576 /* Update the skeletal PDU with the block1 option */
1579 coap_encode_var_safe(buf, sizeof(buf),
1580 (block.num << 4) |
1581 (block.m << 3) |
1582 block.szx),
1583 buf);
1584 /* Update as this is a Request */
1585 lg_xmit->option = COAP_OPTION_BLOCK1;
1586 break;
1587 }
1588 }
1589 }
1590 }
1591
1592#if COAP_Q_BLOCK_SUPPORT
1593 if (COAP_PDU_IS_REQUEST(pdu) &&
1594 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1595 if (block.num == 0 && block.m == 0) {
1596 uint8_t buf[4];
1597
1598 /* M needs to be set as asking for all the blocks */
1600 coap_encode_var_safe(buf, sizeof(buf),
1601 (0 << 4) | (1 << 3) | block.szx),
1602 buf);
1603 }
1604 }
1605#endif /* COAP_Q_BLOCK_SUPPORT */
1606
1607 /*
1608 * If type is CON and protocol is not reliable, there is no need to set up
1609 * lg_crcv here as it can be built up based on sent PDU if there is a
1610 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1611 * (Q-)Block1.
1612 */
1613 if (coap_check_send_need_lg_crcv(session, pdu)) {
1614 coap_lg_xmit_t *lg_xmit = NULL;
1615
1616 if (!session->lg_xmit && have_block1) {
1617 coap_log_debug("PDU presented by app\n");
1619 }
1620 /* See if this token is already in use for large body responses */
1621 LL_FOREACH(session->lg_crcv, lg_crcv) {
1622 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1623 /* Need to terminate and clean up previous response setup */
1624 LL_DELETE(session->lg_crcv, lg_crcv);
1625 coap_block_delete_lg_crcv(session, lg_crcv);
1626 break;
1627 }
1628 }
1629
1630 if (have_block1 && session->lg_xmit) {
1631 LL_FOREACH(session->lg_xmit, lg_xmit) {
1632 if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1633 lg_xmit->b.b1.app_token &&
1634 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1635 break;
1636 }
1637 }
1638 }
1639 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1640 if (lg_crcv == NULL) {
1641 goto error;
1642 }
1643 if (lg_xmit) {
1644 /* Need to update the token as set up in the session->lg_xmit */
1645 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1646 }
1647 }
1648 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1649 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1650
1651#if COAP_Q_BLOCK_SUPPORT
1652 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1653 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1654 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1655 } else
1656#endif /* COAP_Q_BLOCK_SUPPORT */
1657 mid = coap_send_internal(session, pdu, NULL);
1658#else /* !COAP_CLIENT_SUPPORT */
1659 mid = coap_send_internal(session, pdu, NULL);
1660#endif /* !COAP_CLIENT_SUPPORT */
1661#if COAP_CLIENT_SUPPORT
1662 if (lg_crcv) {
1663 if (mid != COAP_INVALID_MID) {
1664 LL_PREPEND(session->lg_crcv, lg_crcv);
1665 } else {
1666 coap_block_delete_lg_crcv(session, lg_crcv);
1667 }
1668 }
1669#endif /* COAP_CLIENT_SUPPORT */
1670 return mid;
1671
1672error:
1674 return COAP_INVALID_MID;
1675}
1676
1677#if COAP_SERVER_SUPPORT
1678static int
1679coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1680 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1681
1682 if (!digest_ctx || !pdu) {
1683 goto fail;
1684 }
1685 if (pdu->used_size && pdu->token) {
1686 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1687 goto fail;
1688 }
1689 }
1690 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1691 goto fail;
1692 }
1693 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1694 goto fail;
1695 }
1696 if (!coap_digest_final(digest_ctx, digest_buffer))
1697 return 0;
1698
1699 return 1;
1700
1701fail:
1702 coap_digest_free(digest_ctx);
1703 return 0;
1704}
1705#endif /* COAP_SERVER_SUPPORT */
1706
1709 uint8_t r;
1710 ssize_t bytes_written;
1711 coap_opt_iterator_t opt_iter;
1712
1713#if ! COAP_SERVER_SUPPORT
1714 (void)request_pdu;
1715#endif /* COAP_SERVER_SUPPORT */
1716 pdu->session = session;
1717 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1718 /*
1719 * Need to prepend our IP identifier to the data as per
1720 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1721 */
1722 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1723 coap_opt_t *opt;
1724 size_t hop_limit;
1725
1726 addr_str[sizeof(addr_str)-1] = '\000';
1727 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1728 sizeof(addr_str) - 1)) {
1729 char *cp;
1730 size_t len;
1731
1732 if (addr_str[0] == '[') {
1733 cp = strchr(addr_str, ']');
1734 if (cp)
1735 *cp = '\000';
1736 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1737 /* IPv4 embedded into IPv6 */
1738 cp = &addr_str[8];
1739 } else {
1740 cp = &addr_str[1];
1741 }
1742 } else {
1743 cp = strchr(addr_str, ':');
1744 if (cp)
1745 *cp = '\000';
1746 cp = addr_str;
1747 }
1748 len = strlen(cp);
1749
1750 /* See if Hop Limit option is being used in return path */
1751 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1752 if (opt) {
1753 uint8_t buf[4];
1754
1755 hop_limit =
1757 if (hop_limit == 1) {
1758 coap_log_warn("Proxy loop detected '%s'\n",
1759 (char *)pdu->data);
1762 } else if (hop_limit < 1 || hop_limit > 255) {
1763 /* Something is bad - need to drop this pdu (TODO or delete option) */
1764 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1765 hop_limit);
1768 }
1769 hop_limit--;
1771 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1772 buf);
1773 }
1774
1775 /* Need to check that we are not seeing this proxy in the return loop */
1776 if (pdu->data && opt == NULL) {
1777 char *a_match;
1778 size_t data_len;
1779
1780 if (pdu->used_size + 1 > pdu->max_size) {
1781 /* No space */
1783 }
1784 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1785 /* Internal error */
1787 }
1788 data_len = pdu->used_size - (pdu->data - pdu->token);
1789 pdu->data[data_len] = '\000';
1790 a_match = strstr((char *)pdu->data, cp);
1791 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1792 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1793 a_match[len] == ' ')) {
1794 coap_log_warn("Proxy loop detected '%s'\n",
1795 (char *)pdu->data);
1798 }
1799 }
1800 if (pdu->used_size + len + 1 <= pdu->max_size) {
1801 size_t old_size = pdu->used_size;
1802 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1803 if (pdu->data == NULL) {
1804 /*
1805 * Set Hop Limit to max for return path. If this libcoap is in
1806 * a proxy loop path, it will always decrement hop limit in code
1807 * above and hence timeout / drop the response as appropriate
1808 */
1809 hop_limit = 255;
1811 (uint8_t *)&hop_limit);
1812 coap_add_data(pdu, len, (uint8_t *)cp);
1813 } else {
1814 /* prepend with space separator, leaving hop limit "as is" */
1815 memmove(pdu->data + len + 1, pdu->data,
1816 old_size - (pdu->data - pdu->token));
1817 memcpy(pdu->data, cp, len);
1818 pdu->data[len] = ' ';
1819 pdu->used_size += len + 1;
1820 }
1821 }
1822 }
1823 }
1824 }
1825
1826 if (session->echo) {
1827 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1828 session->echo->s))
1829 goto error;
1830 coap_delete_bin_const(session->echo);
1831 session->echo = NULL;
1832 }
1833#if COAP_OSCORE_SUPPORT
1834 if (session->oscore_encryption) {
1835 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1837 goto error;
1838 }
1839#endif /* COAP_OSCORE_SUPPORT */
1840
1841 if (!coap_pdu_encode_header(pdu, session->proto)) {
1842 goto error;
1843 }
1844
1845#if !COAP_DISABLE_TCP
1846 if (COAP_PROTO_RELIABLE(session->proto) &&
1848 if (!session->csm_block_supported) {
1849 /*
1850 * Need to check that this instance is not sending any block options as
1851 * the remote end via CSM has not informed us that there is support
1852 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
1853 * This includes potential BERT blocks.
1854 */
1855 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1856 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
1857 }
1858 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1859 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
1860 }
1861 } else if (!session->csm_bert_rem_support) {
1862 coap_opt_t *opt;
1863
1864 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
1865 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1866 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
1867 }
1868 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
1869 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1870 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
1871 }
1872 }
1873 }
1874#endif /* !COAP_DISABLE_TCP */
1875
1876#if COAP_OSCORE_SUPPORT
1877 if (session->oscore_encryption &&
1878 pdu->type != COAP_MESSAGE_RST &&
1879 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
1880 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
1881 /* Refactor PDU as appropriate RFC8613 */
1882 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
1883
1884 if (osc_pdu == NULL) {
1885 coap_log_warn("OSCORE: PDU could not be encrypted\n");
1888 goto error;
1889 }
1890 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
1892 pdu = osc_pdu;
1893 } else
1894#endif /* COAP_OSCORE_SUPPORT */
1895 bytes_written = coap_send_pdu(session, pdu, NULL);
1896
1897#if COAP_SERVER_SUPPORT
1898 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
1899 session->cached_pdu != pdu &&
1900 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
1901 COAP_PDU_IS_REQUEST(request_pdu) &&
1902 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
1904 session->cached_pdu = pdu;
1906 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
1907 }
1908#endif /* COAP_SERVER_SUPPORT */
1909
1910 if (bytes_written == COAP_PDU_DELAYED) {
1911 /* do not free pdu as it is stored with session for later use */
1912 return pdu->mid;
1913 }
1914 if (bytes_written < 0) {
1915 goto error;
1916 }
1917
1918#if !COAP_DISABLE_TCP
1919 if (COAP_PROTO_RELIABLE(session->proto) &&
1920 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1921 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1922 session->partial_write = (size_t)bytes_written;
1923 /* do not free pdu as it is stored with session for later use */
1924 return pdu->mid;
1925 } else {
1926 goto error;
1927 }
1928 }
1929#endif /* !COAP_DISABLE_TCP */
1930
1931 if (pdu->type != COAP_MESSAGE_CON
1932 || COAP_PROTO_RELIABLE(session->proto)) {
1933 coap_mid_t id = pdu->mid;
1935 return id;
1936 }
1937
1938 coap_queue_t *node = coap_new_node();
1939 if (!node) {
1940 coap_log_debug("coap_wait_ack: insufficient memory\n");
1941 goto error;
1942 }
1943
1944 node->id = pdu->mid;
1945 node->pdu = pdu;
1946 coap_prng_lkd(&r, sizeof(r));
1947 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1948 node->timeout = coap_calc_timeout(session, r);
1949 return coap_wait_ack(session->context, session, node);
1950error:
1952 return COAP_INVALID_MID;
1953}
1954
1955static int send_recv_terminate = 0;
1956
1957void
1961
1962COAP_API int
1964 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
1965 int ret;
1966
1967 coap_lock_lock(session->context, return 0);
1968 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
1969 coap_lock_unlock(session->context);
1970 return ret;
1971}
1972
1973/*
1974 * Return 0 or +ve Time in function in ms after successful transfer
1975 * -1 Invalid timeout parameter
1976 * -2 Failed to transmit PDU
1977 * -3 Nack or Event handler invoked, cancelling request
1978 * -4 coap_io_process returned error (fail to re-lock or select())
1979 * -5 Response not received in the given time
1980 * -6 Terminated by user
1981 * -7 Client mode code not enabled
1982 */
1983int
1985 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
1986#if COAP_CLIENT_SUPPORT
1988 uint32_t rem_timeout = timeout_ms;
1989 uint32_t block_mode = session->block_mode;
1990 int ret = 0;
1991 coap_tick_t now;
1992 coap_tick_t start;
1993 coap_tick_t ticks_so_far;
1994 uint32_t time_so_far_ms;
1995
1996 coap_ticks(&start);
1997 assert(request_pdu);
1998
2000
2001 session->resp_pdu = NULL;
2002 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2003 request_pdu->actual_token.length);
2004
2005 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2006 ret = -1;
2007 goto fail;
2008 }
2009 if (session->state == COAP_SESSION_STATE_NONE) {
2010 ret = -3;
2011 goto fail;
2012 }
2013
2015 session->doing_send_recv = 1;
2016 /* So the user needs to delete the PDU */
2017 coap_pdu_reference_lkd(request_pdu);
2018 mid = coap_send_lkd(session, request_pdu);
2019 if (mid == COAP_INVALID_MID) {
2020 if (!session->doing_send_recv)
2021 ret = -3;
2022 else
2023 ret = -2;
2024 goto fail;
2025 }
2026
2027 /* Wait for the response to come in */
2028 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2029 if (send_recv_terminate) {
2030 ret = -6;
2031 goto fail;
2032 }
2033 ret = coap_io_process_lkd(session->context, rem_timeout);
2034 if (ret < 0) {
2035 ret = -4;
2036 goto fail;
2037 }
2038 /* timeout_ms is for timeout between specific request and response */
2039 coap_ticks(&now);
2040 ticks_so_far = now - session->last_rx_tx;
2041 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2042 if (time_so_far_ms >= timeout_ms) {
2043 rem_timeout = 0;
2044 } else {
2045 rem_timeout = timeout_ms - time_so_far_ms;
2046 }
2047 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2048 /* To pick up on (D)TLS setup issues */
2049 coap_ticks(&now);
2050 ticks_so_far = now - start;
2051 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2052 if (time_so_far_ms >= timeout_ms) {
2053 rem_timeout = 0;
2054 } else {
2055 rem_timeout = timeout_ms - time_so_far_ms;
2056 }
2057 }
2058 }
2059
2060 if (rem_timeout) {
2061 coap_ticks(&now);
2062 ticks_so_far = now - start;
2063 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2064 ret = time_so_far_ms;
2065 /* Give PDU to user who will be calling coap_delete_pdu() */
2066 *response_pdu = session->resp_pdu;
2067 session->resp_pdu = NULL;
2068 if (*response_pdu == NULL) {
2069 ret = -3;
2070 }
2071 } else {
2072 /* If there is a resp_pdu, it will get cleared below */
2073 ret = -5;
2074 }
2075
2076fail:
2077 session->block_mode = block_mode;
2078 session->doing_send_recv = 0;
2079 /* delete referenced copy */
2080 coap_delete_pdu_lkd(session->resp_pdu);
2081 session->resp_pdu = NULL;
2083 session->req_token = NULL;
2084 return ret;
2085
2086#else /* !COAP_CLIENT_SUPPORT */
2087
2088 (void)session;
2089 (void)timeout_ms;
2090 (void)request_pdu;
2091 coap_log_warn("coap_send_recv: Client mode not supported\n");
2092 *response_pdu = NULL;
2093 return -7;
2094
2095#endif /* ! COAP_CLIENT_SUPPORT */
2096}
2097
2100 if (!context || !node)
2101 return COAP_INVALID_MID;
2102
2103 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2104 if (node->retransmit_cnt < node->session->max_retransmit) {
2105 ssize_t bytes_written;
2106 coap_tick_t now;
2107 coap_tick_t next_delay;
2108
2109 node->retransmit_cnt++;
2111
2112 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2113 if (context->ping_timeout &&
2114 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2115 uint8_t byte;
2116
2117 coap_prng_lkd(&byte, sizeof(byte));
2118 /* Don't exceed the ping timeout value */
2119 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2120 }
2121
2122 coap_ticks(&now);
2123 if (context->sendqueue == NULL) {
2124 node->t = next_delay;
2125 context->sendqueue_basetime = now;
2126 } else {
2127 /* make node->t relative to context->sendqueue_basetime */
2128 node->t = (now - context->sendqueue_basetime) + next_delay;
2129 }
2130 coap_insert_node(&context->sendqueue, node);
2131
2132 if (node->is_mcast) {
2133 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2134 coap_session_str(node->session), node->id);
2135 } else {
2136 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2137 coap_session_str(node->session), node->id,
2138 node->retransmit_cnt,
2139 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2140 }
2141
2142 if (node->session->con_active)
2143 node->session->con_active--;
2144 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2145
2146 if (node->is_mcast) {
2149 return COAP_INVALID_MID;
2150 }
2151 if (bytes_written == COAP_PDU_DELAYED) {
2152 /* PDU was not retransmitted immediately because a new handshake is
2153 in progress. node was moved to the send queue of the session. */
2154 return node->id;
2155 }
2156
2157 if (bytes_written < 0)
2158 return (int)bytes_written;
2159
2160 return node->id;
2161 }
2162
2163 /* no more retransmissions, remove node from system */
2164 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2165 coap_session_str(node->session), node->id, node->retransmit_cnt);
2166
2167#if COAP_SERVER_SUPPORT
2168 /* Check if subscriptions exist that should be canceled after
2169 COAP_OBS_MAX_FAIL */
2170 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 && node->session->ref_subscriptions) {
2171 if (context->ping_timeout) {
2174 return COAP_INVALID_MID;
2175 } else {
2176 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2177 }
2178 }
2179#endif /* COAP_SERVER_SUPPORT */
2180 if (node->session->con_active) {
2181 node->session->con_active--;
2183 /*
2184 * As there may be another CON in a different queue entry on the same
2185 * session that needs to be immediately released,
2186 * coap_session_connected() is called.
2187 * However, there is the possibility coap_wait_ack() may be called for
2188 * this node (queue) and re-added to context->sendqueue.
2189 * coap_delete_node_lkd(node) called shortly will handle this and
2190 * remove it.
2191 */
2193 }
2194 }
2195
2196 /* And finally delete the node */
2197 if (node->pdu->type == COAP_MESSAGE_CON) {
2199 }
2200#if COAP_CLIENT_SUPPORT
2201 node->session->doing_send_recv = 0;
2202#endif /* COAP_CLIENT_SUPPORT */
2204 return COAP_INVALID_MID;
2205}
2206
2207static int
2209 uint8_t *data;
2210 size_t data_len;
2211 int result = -1;
2212
2213 coap_packet_get_memmapped(packet, &data, &data_len);
2214 if (session->proto == COAP_PROTO_DTLS) {
2215#if COAP_SERVER_SUPPORT
2216 if (session->type == COAP_SESSION_TYPE_HELLO)
2217 result = coap_dtls_hello(session, data, data_len);
2218 else
2219#endif /* COAP_SERVER_SUPPORT */
2220 if (session->tls)
2221 result = coap_dtls_receive(session, data, data_len);
2222 } else if (session->proto == COAP_PROTO_UDP) {
2223 result = coap_handle_dgram(ctx, session, data, data_len);
2224 }
2225 return result;
2226}
2227
2228#if COAP_CLIENT_SUPPORT
2229void
2231#if COAP_DISABLE_TCP
2232 (void)now;
2233
2235#else /* !COAP_DISABLE_TCP */
2236 if (coap_netif_strm_connect2(session)) {
2237 session->last_rx_tx = now;
2239 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2240 } else {
2243 }
2244#endif /* !COAP_DISABLE_TCP */
2245}
2246#endif /* COAP_CLIENT_SUPPORT */
2247
2248static void
2250 (void)ctx;
2251 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2252
2253 while (session->delayqueue) {
2254 ssize_t bytes_written;
2255 coap_queue_t *q = session->delayqueue;
2256 coap_log_debug("** %s: mid=0x%04x: transmitted after delay\n",
2257 coap_session_str(session), (int)q->pdu->mid);
2258 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2259 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2260 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2261 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2262 if (bytes_written > 0)
2263 session->last_rx_tx = now;
2264 if (bytes_written <= 0 ||
2265 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2266 if (bytes_written > 0)
2267 session->partial_write += (size_t)bytes_written;
2268 break;
2269 }
2270 session->delayqueue = q->next;
2271 session->partial_write = 0;
2273 }
2274}
2275
2276void
2278#if COAP_CONSTRAINED_STACK
2279 /* payload and packet can be protected by global_lock if needed */
2280 static unsigned char payload[COAP_RXBUFFER_SIZE];
2281 static coap_packet_t s_packet;
2282#else /* ! COAP_CONSTRAINED_STACK */
2283 unsigned char payload[COAP_RXBUFFER_SIZE];
2284 coap_packet_t s_packet;
2285#endif /* ! COAP_CONSTRAINED_STACK */
2286 coap_packet_t *packet = &s_packet;
2287
2289
2290 packet->length = sizeof(payload);
2291 packet->payload = payload;
2292
2293 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2294 ssize_t bytes_read;
2295 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2296 bytes_read = coap_netif_dgrm_read(session, packet);
2297
2298 if (bytes_read < 0) {
2299 if (bytes_read == -2)
2300 /* Reset the session back to startup defaults */
2302 } else if (bytes_read > 0) {
2303 session->last_rx_tx = now;
2304 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2305 coap_handle_dgram_for_proto(ctx, session, packet);
2306 }
2307#if !COAP_DISABLE_TCP
2308 } else if (session->proto == COAP_PROTO_WS ||
2309 session->proto == COAP_PROTO_WSS) {
2310 ssize_t bytes_read = 0;
2311
2312 /* WebSocket layer passes us the whole packet */
2313 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2314 packet->payload,
2315 packet->length);
2316 if (bytes_read < 0) {
2318 } else if (bytes_read > 2) {
2319 coap_pdu_t *pdu;
2320
2321 session->last_rx_tx = now;
2322 /* Need max space incase PDU is updated with updated token etc. */
2323 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2324 if (!pdu) {
2325 return;
2326 }
2327
2328 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2330 coap_log_warn("discard malformed PDU\n");
2332 return;
2333 }
2334
2335 coap_dispatch(ctx, session, pdu);
2337 return;
2338 }
2339 } else {
2340 ssize_t bytes_read = 0;
2341 const uint8_t *p;
2342 int retry;
2343
2344 do {
2345 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2346 packet->payload,
2347 packet->length);
2348 if (bytes_read > 0) {
2349 session->last_rx_tx = now;
2350 }
2351 p = packet->payload;
2352 retry = bytes_read == (ssize_t)packet->length;
2353 while (bytes_read > 0) {
2354 if (session->partial_pdu) {
2355 size_t len = session->partial_pdu->used_size
2356 + session->partial_pdu->hdr_size
2357 - session->partial_read;
2358 size_t n = min(len, (size_t)bytes_read);
2359 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2360 + session->partial_read, p, n);
2361 p += n;
2362 bytes_read -= n;
2363 if (n == len) {
2364 if (coap_pdu_parse_header(session->partial_pdu, session->proto)
2365 && coap_pdu_parse_opt(session->partial_pdu)) {
2366 coap_dispatch(ctx, session, session->partial_pdu);
2367 }
2369 session->partial_pdu = NULL;
2370 session->partial_read = 0;
2371 } else {
2372 session->partial_read += n;
2373 }
2374 } else if (session->partial_read > 0) {
2375 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2376 session->read_header);
2377 size_t tkl = session->read_header[0] & 0x0f;
2378 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2379 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2380 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2381 size_t n = min(len, (size_t)bytes_read);
2382 memcpy(session->read_header + session->partial_read, p, n);
2383 p += n;
2384 bytes_read -= n;
2385 if (n == len) {
2386 /* Header now all in */
2387 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2388 hdr_size + tok_ext_bytes);
2389 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2390 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2391 coap_session_str(session),
2392 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2393 bytes_read = -1;
2394 break;
2395 }
2396 /* Need max space incase PDU is updated with updated token etc. */
2397 session->partial_pdu = coap_pdu_init(0, 0, 0,
2399 if (session->partial_pdu == NULL) {
2400 bytes_read = -1;
2401 break;
2402 }
2403 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2404 bytes_read = -1;
2405 break;
2406 }
2407 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2408 session->partial_pdu->used_size = size;
2409 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2410 session->partial_read = hdr_size + tok_ext_bytes;
2411 if (size == 0) {
2412 if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
2413 coap_dispatch(ctx, session, session->partial_pdu);
2414 }
2416 session->partial_pdu = NULL;
2417 session->partial_read = 0;
2418 }
2419 } else {
2420 /* More of the header to go */
2421 session->partial_read += n;
2422 }
2423 } else {
2424 /* Get in first byte of the header */
2425 session->read_header[0] = *p++;
2426 bytes_read -= 1;
2427 if (!coap_pdu_parse_header_size(session->proto,
2428 session->read_header)) {
2429 bytes_read = -1;
2430 break;
2431 }
2432 session->partial_read = 1;
2433 }
2434 }
2435 } while (bytes_read == 0 && retry);
2436 if (bytes_read < 0)
2438#endif /* !COAP_DISABLE_TCP */
2439 }
2440}
2441
2442#if COAP_SERVER_SUPPORT
2443static int
2444coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2445 ssize_t bytes_read = -1;
2446 int result = -1; /* the value to be returned */
2447#if COAP_CONSTRAINED_STACK
2448 /* payload and e_packet can be protected by global_lock if needed */
2449 static unsigned char payload[COAP_RXBUFFER_SIZE];
2450 static coap_packet_t e_packet;
2451#else /* ! COAP_CONSTRAINED_STACK */
2452 unsigned char payload[COAP_RXBUFFER_SIZE];
2453 coap_packet_t e_packet;
2454#endif /* ! COAP_CONSTRAINED_STACK */
2455 coap_packet_t *packet = &e_packet;
2456
2457 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2458 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2459
2460 /* Need to do this as there may be holes in addr_info */
2461 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2462 packet->length = sizeof(payload);
2463 packet->payload = payload;
2465 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2466
2467 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2468 if (bytes_read < 0) {
2469 if (errno != EAGAIN) {
2470 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2471 }
2472 } else if (bytes_read > 0) {
2473 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2474 if (session) {
2475 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2476 coap_session_str(session), bytes_read);
2477 result = coap_handle_dgram_for_proto(ctx, session, packet);
2478 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2479 coap_session_new_dtls_session(session, now);
2480 }
2481 }
2482 return result;
2483}
2484
2485static int
2486coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2487 (void)ctx;
2488 (void)endpoint;
2489 (void)now;
2490 return 0;
2491}
2492
2493#if !COAP_DISABLE_TCP
2494static int
2495coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2496 coap_tick_t now, void *extra) {
2497 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2498 if (session)
2499 session->last_rx_tx = now;
2500 return session != NULL;
2501}
2502#endif /* !COAP_DISABLE_TCP */
2503#endif /* COAP_SERVER_SUPPORT */
2504
2505COAP_API void
2507 coap_lock_lock(ctx, return);
2508 coap_io_do_io_lkd(ctx, now);
2509 coap_lock_unlock(ctx);
2510}
2511
2512void
2514#ifdef COAP_EPOLL_SUPPORT
2515 (void)ctx;
2516 (void)now;
2517 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2518#else /* ! COAP_EPOLL_SUPPORT */
2519 coap_session_t *s, *rtmp;
2520
2522#if COAP_SERVER_SUPPORT
2523 coap_endpoint_t *ep, *tmp;
2524 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2525 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2526 coap_read_endpoint(ctx, ep, now);
2527 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2528 coap_write_endpoint(ctx, ep, now);
2529#if !COAP_DISABLE_TCP
2530 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2531 coap_accept_endpoint(ctx, ep, now, NULL);
2532#endif /* !COAP_DISABLE_TCP */
2533 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2534 /* Make sure the session object is not deleted in one of the callbacks */
2536 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2537 coap_read_session(ctx, s, now);
2538 }
2539 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2540 coap_write_session(ctx, s, now);
2541 }
2543 }
2544 }
2545#endif /* COAP_SERVER_SUPPORT */
2546
2547#if COAP_CLIENT_SUPPORT
2548 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2549 /* Make sure the session object is not deleted in one of the callbacks */
2551 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2552 coap_connect_session(s, now);
2553 }
2554 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2555 coap_read_session(ctx, s, now);
2556 }
2557 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2558 coap_write_session(ctx, s, now);
2559 }
2561 }
2562#endif /* COAP_CLIENT_SUPPORT */
2563#endif /* ! COAP_EPOLL_SUPPORT */
2564}
2565
2566COAP_API void
2567coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2568 coap_lock_lock(ctx, return);
2569 coap_io_do_epoll_lkd(ctx, events, nevents);
2570 coap_lock_unlock(ctx);
2571}
2572
2573/*
2574 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2575 * directly saves having to iterate through the endpoints / sessions.
2576 */
2577void
2578coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2579#ifndef COAP_EPOLL_SUPPORT
2580 (void)ctx;
2581 (void)events;
2582 (void)nevents;
2583 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2584#else /* COAP_EPOLL_SUPPORT */
2585 coap_tick_t now;
2586 size_t j;
2587
2589 coap_ticks(&now);
2590 for (j = 0; j < nevents; j++) {
2591 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2592
2593 /* Ignore 'timer trigger' ptr which is NULL */
2594 if (sock) {
2595#if COAP_SERVER_SUPPORT
2596 if (sock->endpoint) {
2597 coap_endpoint_t *endpoint = sock->endpoint;
2598 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2599 (events[j].events & EPOLLIN)) {
2600 sock->flags |= COAP_SOCKET_CAN_READ;
2601 coap_read_endpoint(endpoint->context, endpoint, now);
2602 }
2603
2604 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2605 (events[j].events & EPOLLOUT)) {
2606 /*
2607 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2608 * be true causing epoll_wait to return early
2609 */
2610 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2612 coap_write_endpoint(endpoint->context, endpoint, now);
2613 }
2614
2615#if !COAP_DISABLE_TCP
2616 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2617 (events[j].events & EPOLLIN)) {
2619 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2620 }
2621#endif /* !COAP_DISABLE_TCP */
2622
2623 } else
2624#endif /* COAP_SERVER_SUPPORT */
2625 if (sock->session) {
2626 coap_session_t *session = sock->session;
2627
2628 /* Make sure the session object is not deleted
2629 in one of the callbacks */
2631#if COAP_CLIENT_SUPPORT
2632 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2633 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2635 coap_connect_session(session, now);
2636 if (coap_netif_available(session) &&
2637 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2638 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2639 }
2640 }
2641#endif /* COAP_CLIENT_SUPPORT */
2642
2643 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2644 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2645 sock->flags |= COAP_SOCKET_CAN_READ;
2646 coap_read_session(session->context, session, now);
2647 }
2648
2649 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2650 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2651 /*
2652 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2653 * be true causing epoll_wait to return early
2654 */
2655 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2657 coap_write_session(session->context, session, now);
2658 }
2659 /* Now dereference session so it can go away if needed */
2660 coap_session_release_lkd(session);
2661 }
2662 } else if (ctx->eptimerfd != -1) {
2663 /*
2664 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2665 * it so that it does not set EPOLLIN in the next epoll_wait().
2666 */
2667 uint64_t count;
2668
2669 /* Check the result from read() to suppress the warning on
2670 * systems that declare read() with warn_unused_result. */
2671 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2672 /* do nothing */;
2673 }
2674 }
2675 }
2676 /* And update eptimerfd as to when to next trigger */
2677 coap_ticks(&now);
2678 coap_io_prepare_epoll_lkd(ctx, now);
2679#endif /* COAP_EPOLL_SUPPORT */
2680}
2681
2682int
2684 uint8_t *msg, size_t msg_len) {
2685
2686 coap_pdu_t *pdu = NULL;
2687
2688 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2689 if (msg_len < 4) {
2690 /* Minimum size of CoAP header - ignore runt */
2691 return -1;
2692 }
2693 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2694 /*
2695 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2696 * this MUST be silently ignored.
2697 */
2698 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2699 return -1;
2700 }
2701
2702 /* Need max space incase PDU is updated with updated token etc. */
2703 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2704 if (!pdu)
2705 goto error;
2706
2707 if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
2709 coap_log_warn("discard malformed PDU\n");
2710 goto error;
2711 }
2712
2713 coap_dispatch(ctx, session, pdu);
2715 return 0;
2716
2717error:
2718 /*
2719 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2720 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2721 */
2722 coap_send_rst_lkd(session, pdu);
2724 return -1;
2725}
2726
2727int
2729 coap_queue_t **node) {
2730 coap_queue_t *p, *q;
2731
2732 if (!queue || !*queue)
2733 return 0;
2734
2735 /* replace queue head if PDU's time is less than head's time */
2736
2737 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2738 *node = *queue;
2739 *queue = (*queue)->next;
2740 if (*queue) { /* adjust relative time of new queue head */
2741 (*queue)->t += (*node)->t;
2742 }
2743 (*node)->next = NULL;
2744 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2745 coap_session_str(session), id);
2746 return 1;
2747 }
2748
2749 /* search message id in queue to remove (only first occurence will be removed) */
2750 q = *queue;
2751 do {
2752 p = q;
2753 q = q->next;
2754 } while (q && (session != q->session || id != q->id));
2755
2756 if (q) { /* found message id */
2757 p->next = q->next;
2758 if (p->next) { /* must update relative time of p->next */
2759 p->next->t += q->t;
2760 }
2761 q->next = NULL;
2762 *node = q;
2763 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2764 coap_session_str(session), id);
2765 return 1;
2766 }
2767
2768 return 0;
2769
2770}
2771
2772static int
2774 coap_bin_const_t *token, coap_queue_t **node) {
2775 coap_queue_t *p, *q;
2776
2777 if (!queue || !*queue)
2778 return 0;
2779
2780 /* replace queue head if PDU's time is less than head's time */
2781
2782 if (session == (*queue)->session &&
2783 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
2784 *node = *queue;
2785 *queue = (*queue)->next;
2786 if (*queue) { /* adjust relative time of new queue head */
2787 (*queue)->t += (*node)->t;
2788 }
2789 (*node)->next = NULL;
2790 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
2791 coap_session_str(session), (*node)->id);
2792 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2793 session->con_active--;
2794 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2795 /* Flush out any entries on session->delayqueue */
2796 coap_session_connected(session);
2797 }
2798 return 1;
2799 }
2800
2801 /* search token in queue to remove (only first occurence will be removed) */
2802 q = *queue;
2803 do {
2804 p = q;
2805 q = q->next;
2806 } while (q && (session != q->session ||
2807 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
2808
2809 if (q) { /* found token */
2810 p->next = q->next;
2811 if (p->next) { /* must update relative time of p->next */
2812 p->next->t += q->t;
2813 }
2814 q->next = NULL;
2815 *node = q;
2816 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
2817 coap_session_str(session), (*node)->id);
2818 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2819 session->con_active--;
2820 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2821 /* Flush out any entries on session->delayqueue */
2822 coap_session_connected(session);
2823 }
2824 return 1;
2825 }
2826
2827 return 0;
2828
2829}
2830
2831void
2833 coap_nack_reason_t reason) {
2834 coap_queue_t *p, *q;
2835
2836 while (context->sendqueue && context->sendqueue->session == session) {
2837 q = context->sendqueue;
2838 context->sendqueue = q->next;
2839 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
2840 coap_session_str(session), q->id);
2841 if (q->pdu->type == COAP_MESSAGE_CON) {
2842 coap_handle_nack(session, q->pdu, reason, q->id);
2843 }
2845 }
2846
2847 if (!context->sendqueue)
2848 return;
2849
2850 p = context->sendqueue;
2851 q = p->next;
2852
2853 while (q) {
2854 if (q->session == session) {
2855 p->next = q->next;
2856 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
2857 coap_session_str(session), q->id);
2858 if (q->pdu->type == COAP_MESSAGE_CON) {
2859 coap_handle_nack(session, q->pdu, reason, q->id);
2860 }
2862 q = p->next;
2863 } else {
2864 p = q;
2865 q = q->next;
2866 }
2867 }
2868}
2869
2870void
2872 coap_bin_const_t *token) {
2873 /* cancel all messages in sendqueue that belong to session
2874 * and use the specified token */
2875 coap_queue_t **p, *q;
2876
2877 if (!context->sendqueue)
2878 return;
2879
2880 p = &context->sendqueue;
2881 q = *p;
2882
2883 while (q) {
2884 if (q->session == session &&
2885 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
2886 *p = q->next;
2887 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
2888 coap_session_str(session), q->id);
2889 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2890 session->con_active--;
2891 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2892 /* Flush out any entries on session->delayqueue */
2893 coap_session_connected(session);
2894 }
2896 } else {
2897 p = &(q->next);
2898 }
2899 q = *p;
2900 }
2901}
2902
2903coap_pdu_t *
2905 coap_opt_filter_t *opts) {
2906 coap_opt_iterator_t opt_iter;
2907 coap_pdu_t *response;
2908 size_t size = request->e_token_length;
2909 unsigned char type;
2910 coap_opt_t *option;
2911 coap_option_num_t opt_num = 0; /* used for calculating delta-storage */
2912
2913#if COAP_ERROR_PHRASE_LENGTH > 0
2914 const char *phrase;
2915 if (code != COAP_RESPONSE_CODE(508)) {
2916 phrase = coap_response_phrase(code);
2917
2918 /* Need some more space for the error phrase and payload start marker */
2919 if (phrase)
2920 size += strlen(phrase) + 1;
2921 } else {
2922 /*
2923 * Need space for IP for 5.08 response which is filled in in
2924 * coap_send_internal()
2925 * https://rfc-editor.org/rfc/rfc8768.html#section-4
2926 */
2927 phrase = NULL;
2928 size += INET6_ADDRSTRLEN;
2929 }
2930#endif
2931
2932 assert(request);
2933
2934 /* cannot send ACK if original request was not confirmable */
2935 type = request->type == COAP_MESSAGE_CON ?
2937
2938 /* Estimate how much space we need for options to copy from
2939 * request. We always need the Token, for 4.02 the unknown critical
2940 * options must be included as well. */
2941
2942 /* we do not want these */
2945 /* Unsafe to send this back */
2947
2948 coap_option_iterator_init(request, &opt_iter, opts);
2949
2950 /* Add size of each unknown critical option. As known critical
2951 options as well as elective options are not copied, the delta
2952 value might grow.
2953 */
2954 while ((option = coap_option_next(&opt_iter))) {
2955 uint16_t delta = opt_iter.number - opt_num;
2956 /* calculate space required to encode (opt_iter.number - opt_num) */
2957 if (delta < 13) {
2958 size++;
2959 } else if (delta < 269) {
2960 size += 2;
2961 } else {
2962 size += 3;
2963 }
2964
2965 /* add coap_opt_length(option) and the number of additional bytes
2966 * required to encode the option length */
2967
2968 size += coap_opt_length(option);
2969 switch (*option & 0x0f) {
2970 case 0x0e:
2971 size++;
2972 /* fall through */
2973 case 0x0d:
2974 size++;
2975 break;
2976 default:
2977 ;
2978 }
2979
2980 opt_num = opt_iter.number;
2981 }
2982
2983 /* Now create the response and fill with options and payload data. */
2984 response = coap_pdu_init(type, code, request->mid, size);
2985 if (response) {
2986 /* copy token */
2987 if (!coap_add_token(response, request->actual_token.length,
2988 request->actual_token.s)) {
2989 coap_log_debug("cannot add token to error response\n");
2990 coap_delete_pdu_lkd(response);
2991 return NULL;
2992 }
2993
2994 /* copy all options */
2995 coap_option_iterator_init(request, &opt_iter, opts);
2996 while ((option = coap_option_next(&opt_iter))) {
2997 coap_add_option_internal(response, opt_iter.number,
2998 coap_opt_length(option),
2999 coap_opt_value(option));
3000 }
3001
3002#if COAP_ERROR_PHRASE_LENGTH > 0
3003 /* note that diagnostic messages do not need a Content-Format option. */
3004 if (phrase)
3005 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3006#endif
3007 }
3008
3009 return response;
3010}
3011
3012#if COAP_SERVER_SUPPORT
3013#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3014
3015static void
3016free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3017 coap_delete_string(app_ptr);
3018}
3019
3020/*
3021 * Caution: As this handler is in libcoap space, it is called with
3022 * context locked.
3023 */
3024static void
3025hnd_get_wellknown_lkd(coap_resource_t *resource,
3026 coap_session_t *session,
3027 const coap_pdu_t *request,
3028 const coap_string_t *query,
3029 coap_pdu_t *response) {
3030 size_t len = 0;
3031 coap_string_t *data_string = NULL;
3032 coap_print_status_t result = 0;
3033 size_t wkc_len = 0;
3034 uint8_t buf[4];
3035
3036 /*
3037 * Quick hack to determine the size of the resource descriptions for
3038 * .well-known/core.
3039 */
3040 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3041 if (result & COAP_PRINT_STATUS_ERROR) {
3042 coap_log_warn("cannot determine length of /.well-known/core\n");
3043 goto error;
3044 }
3045
3046 if (wkc_len > 0) {
3047 data_string = coap_new_string(wkc_len);
3048 if (!data_string)
3049 goto error;
3050
3051 len = wkc_len;
3052 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3053 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3054 coap_log_debug("coap_print_wellknown failed\n");
3055 goto error;
3056 }
3057 assert(len <= (size_t)wkc_len);
3058 data_string->length = len;
3059
3060 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3062 coap_encode_var_safe(buf, sizeof(buf),
3064 goto error;
3065 }
3066 if (response->used_size + len + 1 > response->max_size) {
3067 /*
3068 * Data does not fit into a packet and no libcoap block support
3069 * +1 for end of options marker
3070 */
3071 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
3072 len, response->max_size - response->used_size - 1);
3073 len = response->max_size - response->used_size - 1;
3074 }
3075 if (!coap_add_data(response, len, data_string->s)) {
3076 goto error;
3077 }
3078 free_wellknown_response(session, data_string);
3079 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3080 response, query,
3082 -1, 0, data_string->length,
3083 data_string->s,
3084 free_wellknown_response,
3085 data_string)) {
3086 goto error_released;
3087 }
3088 } else {
3090 coap_encode_var_safe(buf, sizeof(buf),
3092 goto error;
3093 }
3094 }
3095 response->code = COAP_RESPONSE_CODE(205);
3096 return;
3097
3098error:
3099 free_wellknown_response(session, data_string);
3100error_released:
3101 if (response->code == 0) {
3102 /* set error code 5.03 and remove all options and data from response */
3103 response->code = COAP_RESPONSE_CODE(503);
3104 response->used_size = response->e_token_length;
3105 response->data = NULL;
3106 }
3107}
3108#endif /* COAP_SERVER_SUPPORT */
3109
3120static int
3122 int num_cancelled = 0; /* the number of observers cancelled */
3123
3124#ifndef COAP_SERVER_SUPPORT
3125 (void)sent;
3126#endif /* ! COAP_SERVER_SUPPORT */
3127 (void)context;
3128
3129#if COAP_SERVER_SUPPORT
3130 /* remove observer for this resource, if any
3131 * Use token from sent and try to find a matching resource. Uh!
3132 */
3133 RESOURCES_ITER(context->resources, r) {
3134 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3135 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3136 }
3137#endif /* COAP_SERVER_SUPPORT */
3138
3139 return num_cancelled;
3140}
3141
3142#if COAP_SERVER_SUPPORT
3147enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3148
3149/*
3150 * Checks for No-Response option in given @p request and
3151 * returns @c RESPONSE_DROP if @p response should be suppressed
3152 * according to RFC 7967.
3153 *
3154 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3155 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3156 * on retrying.
3157 *
3158 * Checks if the response code is 0.00 and if either the session is reliable or
3159 * non-confirmable, @c RESPONSE_DROP is also returned.
3160 *
3161 * Multicast response checking is also carried out.
3162 *
3163 * NOTE: It is the responsibility of the application to determine whether
3164 * a delayed separate response should be sent as the original requesting packet
3165 * containing the No-Response option has long since gone.
3166 *
3167 * The value of the No-Response option is encoded as
3168 * follows:
3169 *
3170 * @verbatim
3171 * +-------+-----------------------+-----------------------------------+
3172 * | Value | Binary Representation | Description |
3173 * +-------+-----------------------+-----------------------------------+
3174 * | 0 | <empty> | Interested in all responses. |
3175 * +-------+-----------------------+-----------------------------------+
3176 * | 2 | 00000010 | Not interested in 2.xx responses. |
3177 * +-------+-----------------------+-----------------------------------+
3178 * | 8 | 00001000 | Not interested in 4.xx responses. |
3179 * +-------+-----------------------+-----------------------------------+
3180 * | 16 | 00010000 | Not interested in 5.xx responses. |
3181 * +-------+-----------------------+-----------------------------------+
3182 * @endverbatim
3183 *
3184 * @param request The CoAP request to check for the No-Response option.
3185 * This parameter must not be NULL.
3186 * @param response The response that is potentially suppressed.
3187 * This parameter must not be NULL.
3188 * @param session The session this request/response are associated with.
3189 * This parameter must not be NULL.
3190 * @return RESPONSE_DEFAULT when no special treatment is requested,
3191 * RESPONSE_DROP when the response must be discarded, or
3192 * RESPONSE_SEND when the response must be sent.
3193 */
3194static enum respond_t
3195no_response(coap_pdu_t *request, coap_pdu_t *response,
3196 coap_session_t *session, coap_resource_t *resource) {
3197 coap_opt_t *nores;
3198 coap_opt_iterator_t opt_iter;
3199 unsigned int val = 0;
3200
3201 assert(request);
3202 assert(response);
3203
3204 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3205 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3206
3207 if (nores) {
3209
3210 /* The response should be dropped when the bit corresponding to
3211 * the response class is set (cf. table in function
3212 * documentation). When a No-Response option is present and the
3213 * bit is not set, the sender explicitly indicates interest in
3214 * this response. */
3215 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3216 /* Should be dropping the response */
3217 if (response->type == COAP_MESSAGE_ACK &&
3218 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3219 /* Still need to ACK the request */
3220 response->code = 0;
3221 /* Remove token/data from piggybacked acknowledgment PDU */
3222 response->actual_token.length = 0;
3223 response->e_token_length = 0;
3224 response->used_size = 0;
3225 response->data = NULL;
3226 return RESPONSE_SEND;
3227 } else {
3228 return RESPONSE_DROP;
3229 }
3230 } else {
3231 /* True for mcast as well RFC7967 2.1 */
3232 return RESPONSE_SEND;
3233 }
3234 } else if (resource && session->context->mcast_per_resource &&
3235 coap_is_mcast(&session->addr_info.local)) {
3236 /* Handle any mcast suppression specifics if no NoResponse option */
3237 if ((resource->flags &
3239 COAP_RESPONSE_CLASS(response->code) == 2) {
3240 return RESPONSE_DROP;
3241 } else if ((resource->flags &
3243 response->code == COAP_RESPONSE_CODE(205)) {
3244 if (response->data == NULL)
3245 return RESPONSE_DROP;
3246 } else if ((resource->flags &
3248 COAP_RESPONSE_CLASS(response->code) == 4) {
3249 return RESPONSE_DROP;
3250 } else if ((resource->flags &
3252 COAP_RESPONSE_CLASS(response->code) == 5) {
3253 return RESPONSE_DROP;
3254 }
3255 }
3256 } else if (COAP_PDU_IS_EMPTY(response) &&
3257 (response->type == COAP_MESSAGE_NON ||
3258 COAP_PROTO_RELIABLE(session->proto))) {
3259 /* response is 0.00, and this is reliable or non-confirmable */
3260 return RESPONSE_DROP;
3261 }
3262
3263 /*
3264 * Do not send error responses for requests that were received via
3265 * IP multicast. RFC7252 8.1
3266 */
3267
3268 if (coap_is_mcast(&session->addr_info.local)) {
3269 if (request->type == COAP_MESSAGE_NON &&
3270 response->type == COAP_MESSAGE_RST)
3271 return RESPONSE_DROP;
3272
3273 if ((!resource || session->context->mcast_per_resource == 0) &&
3274 COAP_RESPONSE_CLASS(response->code) > 2)
3275 return RESPONSE_DROP;
3276 }
3277
3278 /* Default behavior applies when we are not dealing with a response
3279 * (class == 0) or the request did not contain a No-Response option.
3280 */
3281 return RESPONSE_DEFAULT;
3282}
3283
3284static coap_str_const_t coap_default_uri_wellknown = {
3286 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3287};
3288
3289/* Initialized in coap_startup() */
3290static coap_resource_t resource_uri_wellknown;
3291
3292static void
3293handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3294 coap_pdu_t *orig_pdu) {
3295 coap_method_handler_t h = NULL;
3296 coap_pdu_t *response = NULL;
3297 coap_opt_filter_t opt_filter;
3298 coap_resource_t *resource = NULL;
3299 /* The respond field indicates whether a response must be treated
3300 * specially due to a No-Response option that declares disinterest
3301 * or interest in a specific response class. DEFAULT indicates that
3302 * No-Response has not been specified. */
3303 enum respond_t respond = RESPONSE_DEFAULT;
3304 coap_opt_iterator_t opt_iter;
3305 coap_opt_t *opt;
3306 int is_proxy_uri = 0;
3307 int is_proxy_scheme = 0;
3308 int skip_hop_limit_check = 0;
3309 int resp = 0;
3310 int send_early_empty_ack = 0;
3311 coap_string_t *query = NULL;
3312 coap_opt_t *observe = NULL;
3313 coap_string_t *uri_path = NULL;
3314 int observe_action = COAP_OBSERVE_CANCEL;
3315 coap_block_b_t block;
3316 int added_block = 0;
3317 coap_lg_srcv_t *free_lg_srcv = NULL;
3318#if COAP_Q_BLOCK_SUPPORT
3319 int lg_xmit_ctrl = 0;
3320#endif /* COAP_Q_BLOCK_SUPPORT */
3321#if COAP_ASYNC_SUPPORT
3322 coap_async_t *async;
3323#endif /* COAP_ASYNC_SUPPORT */
3324
3325 if (coap_is_mcast(&session->addr_info.local)) {
3326 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3327 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3328 return;
3329 }
3330 }
3331#if COAP_ASYNC_SUPPORT
3332 async = coap_find_async_lkd(session, pdu->actual_token);
3333 if (async) {
3334 coap_tick_t now;
3335
3336 coap_ticks(&now);
3337 if (async->delay == 0 || async->delay > now) {
3338 /* re-transmit missing ACK (only if CON) */
3339 coap_log_info("Retransmit async response\n");
3340 coap_send_ack_lkd(session, pdu);
3341 /* and do not pass on to the upper layers */
3342 return;
3343 }
3344 }
3345#endif /* COAP_ASYNC_SUPPORT */
3346
3347 coap_option_filter_clear(&opt_filter);
3348 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3349 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3350 if (opt) {
3351 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3352 if (!opt) {
3353 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3354 resp = 402;
3355 goto fail_response;
3356 }
3357 is_proxy_scheme = 1;
3358 }
3359
3360 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3361 if (opt)
3362 is_proxy_uri = 1;
3363 }
3364
3365 if (is_proxy_scheme || is_proxy_uri) {
3366 coap_uri_t uri;
3367
3368 if (!context->proxy_uri_resource) {
3369 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3370 coap_log_debug("Proxy-%s support not configured\n",
3371 is_proxy_scheme ? "Scheme" : "Uri");
3372 resp = 505;
3373 goto fail_response;
3374 }
3375 if (((size_t)pdu->code - 1 <
3376 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3377 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3378 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3379 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3380 is_proxy_scheme ? "Scheme" : "Uri",
3381 pdu->code/100, pdu->code%100);
3382 resp = 505;
3383 goto fail_response;
3384 }
3385
3386 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3387 if (is_proxy_uri) {
3389 coap_opt_length(opt), &uri) < 0) {
3390 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3391 coap_log_debug("Proxy-URI not decodable\n");
3392 resp = 505;
3393 goto fail_response;
3394 }
3395 } else {
3396 memset(&uri, 0, sizeof(uri));
3397 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3398 if (opt) {
3399 uri.host.length = coap_opt_length(opt);
3400 uri.host.s = coap_opt_value(opt);
3401 } else
3402 uri.host.length = 0;
3403 }
3404
3405 resource = context->proxy_uri_resource;
3406 if (uri.host.length && resource->proxy_name_count &&
3407 resource->proxy_name_list) {
3408 size_t i;
3409
3410 if (resource->proxy_name_count == 1 &&
3411 resource->proxy_name_list[0]->length == 0) {
3412 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3413 i = 0;
3414 } else {
3415 for (i = 0; i < resource->proxy_name_count; i++) {
3416 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3417 break;
3418 }
3419 }
3420 }
3421 if (i != resource->proxy_name_count) {
3422 /* This server is hosting the proxy connection endpoint */
3423 if (pdu->crit_opt) {
3424 /* Cannot handle critical option */
3425 pdu->crit_opt = 0;
3426 resp = 402;
3427 goto fail_response;
3428 }
3429 is_proxy_uri = 0;
3430 is_proxy_scheme = 0;
3431 skip_hop_limit_check = 1;
3432 }
3433 }
3434 resource = NULL;
3435 }
3436
3437 if (!skip_hop_limit_check) {
3438 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3439 if (opt) {
3440 size_t hop_limit;
3441 uint8_t buf[4];
3442
3443 hop_limit =
3445 if (hop_limit == 1) {
3446 /* coap_send_internal() will fill in the IP address for us */
3447 resp = 508;
3448 goto fail_response;
3449 } else if (hop_limit < 1 || hop_limit > 255) {
3450 /* Need to return a 4.00 RFC8768 Section 3 */
3451 coap_log_info("Invalid Hop Limit\n");
3452 resp = 400;
3453 goto fail_response;
3454 }
3455 hop_limit--;
3457 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3458 buf);
3459 }
3460 }
3461
3462 uri_path = coap_get_uri_path(pdu);
3463 if (!uri_path)
3464 return;
3465
3466 if (!is_proxy_uri && !is_proxy_scheme) {
3467 /* try to find the resource from the request URI */
3468 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3469 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3470 }
3471
3472 if ((resource == NULL) || (resource->is_unknown == 1) ||
3473 (resource->is_proxy_uri == 1)) {
3474 /* The resource was not found or there is an unexpected match against the
3475 * resource defined for handling unknown or proxy URIs.
3476 */
3477 if (resource != NULL)
3478 /* Close down unexpected match */
3479 resource = NULL;
3480 /*
3481 * Check if the request URI happens to be the well-known URI, or if the
3482 * unknown resource handler is defined, a PUT or optionally other methods,
3483 * if configured, for the unknown handler.
3484 *
3485 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3486 * proxy URI handler.
3487 *
3488 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3489 * set, call the unknown URI handler with any unknown URI (including
3490 * .well-known/core) if the appropriate method is defined.
3491 *
3492 * else if well-known URI generate a default response.
3493 *
3494 * else if unknown URI handler defined, call the unknown
3495 * URI handler (to allow for potential generation of resource
3496 * [RFC7272 5.8.3]) if the appropriate method is defined.
3497 *
3498 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3499 *
3500 * else return 4.04.
3501 */
3502
3503 if (is_proxy_uri || is_proxy_scheme) {
3504 resource = context->proxy_uri_resource;
3505 } else if (context->unknown_resource != NULL &&
3507 ((size_t)pdu->code - 1 <
3508 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3509 (context->unknown_resource->handler[pdu->code - 1])) {
3510 resource = context->unknown_resource;
3511 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3512 /* request for .well-known/core */
3513 resource = &resource_uri_wellknown;
3514 } else if ((context->unknown_resource != NULL) &&
3515 ((size_t)pdu->code - 1 <
3516 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3517 (context->unknown_resource->handler[pdu->code - 1])) {
3518 /*
3519 * The unknown_resource can be used to handle undefined resources
3520 * for a PUT request and can support any other registered handler
3521 * defined for it
3522 * Example set up code:-
3523 * r = coap_resource_unknown_init(hnd_put_unknown);
3524 * coap_register_request_handler(r, COAP_REQUEST_POST,
3525 * hnd_post_unknown);
3526 * coap_register_request_handler(r, COAP_REQUEST_GET,
3527 * hnd_get_unknown);
3528 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3529 * hnd_delete_unknown);
3530 * coap_add_resource(ctx, r);
3531 *
3532 * Note: It is not possible to observe the unknown_resource, a separate
3533 * resource must be created (by PUT or POST) which has a GET
3534 * handler to be observed
3535 */
3536 resource = context->unknown_resource;
3537 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3538 /*
3539 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3540 */
3541 coap_log_debug("request for unknown resource '%*.*s',"
3542 " return 2.02\n",
3543 (int)uri_path->length,
3544 (int)uri_path->length,
3545 uri_path->s);
3546 resp = 202;
3547 goto fail_response;
3548 } else { /* request for any another resource, return 4.04 */
3549
3550 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3551 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3552 resp = 404;
3553 goto fail_response;
3554 }
3555
3556 }
3557
3558#if COAP_OSCORE_SUPPORT
3559 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3560 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3561 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3562 resp = 401;
3563 goto fail_response;
3564 }
3565#endif /* COAP_OSCORE_SUPPORT */
3566 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3567 /* Check for existing resource and If-Non-Match */
3568 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3569 if (opt) {
3570 resp = 412;
3571 goto fail_response;
3572 }
3573 }
3574
3575 /* the resource was found, check if there is a registered handler */
3576 if ((size_t)pdu->code - 1 <
3577 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3578 h = resource->handler[pdu->code - 1];
3579
3580 if (h == NULL) {
3581 resp = 405;
3582 goto fail_response;
3583 }
3584 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3585 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3586 if (opt == NULL) {
3587 /* RFC 8132 2.3.1 */
3588 resp = 415;
3589 goto fail_response;
3590 }
3591 }
3592 if (context->mcast_per_resource &&
3593 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3594 coap_is_mcast(&session->addr_info.local)) {
3595 resp = 405;
3596 goto fail_response;
3597 }
3598
3599 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3601 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3602 if (!response) {
3603 coap_log_err("could not create response PDU\n");
3604 resp = 500;
3605 goto fail_response;
3606 }
3607 response->session = session;
3608#if COAP_ASYNC_SUPPORT
3609 /* If handling a separate response, need CON, not ACK response */
3610 if (async && pdu->type == COAP_MESSAGE_CON)
3611 response->type = COAP_MESSAGE_CON;
3612#endif /* COAP_ASYNC_SUPPORT */
3613 /* A lot of the reliable code assumes type is CON */
3614 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3615 response->type = COAP_MESSAGE_CON;
3616
3617 if (!coap_add_token(response, pdu->actual_token.length,
3618 pdu->actual_token.s)) {
3619 resp = 500;
3620 goto fail_response;
3621 }
3622
3623 query = coap_get_query(pdu);
3624
3625 /* check for Observe option RFC7641 and RFC8132 */
3626 if (resource->observable &&
3627 (pdu->code == COAP_REQUEST_CODE_GET ||
3628 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3629 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3630 }
3631
3632 /*
3633 * See if blocks need to be aggregated or next requests sent off
3634 * before invoking application request handler
3635 */
3636 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3637 uint32_t block_mode = session->block_mode;
3638
3639 if (observe ||
3642 if (coap_handle_request_put_block(context, session, pdu, response,
3643 resource, uri_path, observe,
3644 &added_block, &free_lg_srcv)) {
3645 session->block_mode = block_mode;
3646 goto skip_handler;
3647 }
3648 session->block_mode = block_mode;
3649
3650 if (coap_handle_request_send_block(session, pdu, response, resource,
3651 query)) {
3652#if COAP_Q_BLOCK_SUPPORT
3653 lg_xmit_ctrl = 1;
3654#endif /* COAP_Q_BLOCK_SUPPORT */
3655 goto skip_handler;
3656 }
3657 }
3658
3659 if (observe) {
3660 observe_action =
3662 coap_opt_length(observe));
3663
3664 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3665 coap_subscription_t *subscription;
3666
3667 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3668 if (block.num != 0) {
3669 response->code = COAP_RESPONSE_CODE(400);
3670 goto skip_handler;
3671 }
3672#if COAP_Q_BLOCK_SUPPORT
3673 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3674 &block)) {
3675 if (block.num != 0) {
3676 response->code = COAP_RESPONSE_CODE(400);
3677 goto skip_handler;
3678 }
3679#endif /* COAP_Q_BLOCK_SUPPORT */
3680 }
3681 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3682 pdu);
3683 if (subscription) {
3684 uint8_t buf[4];
3685
3686 coap_touch_observer(context, session, &pdu->actual_token);
3688 coap_encode_var_safe(buf, sizeof(buf),
3689 resource->observe),
3690 buf);
3691 }
3692 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3693 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3694 } else {
3695 coap_log_info("observe: unexpected action %d\n", observe_action);
3696 }
3697 }
3698
3699 if ((resource == context->proxy_uri_resource ||
3700 (resource == context->unknown_resource &&
3701 context->unknown_resource->is_reverse_proxy)) &&
3702 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3703 pdu->type == COAP_MESSAGE_CON &&
3704 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3705 /* Make the proxy response separate and fix response later */
3706 send_early_empty_ack = 1;
3707 }
3708 if (send_early_empty_ack) {
3709 coap_send_ack_lkd(session, pdu);
3710 if (pdu->mid == session->last_con_mid) {
3711 /* request has already been processed - do not process it again */
3712 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3713 pdu->mid);
3714 goto drop_it_no_debug;
3715 }
3716 session->last_con_mid = pdu->mid;
3717 }
3718#if COAP_WITH_OBSERVE_PERSIST
3719 /* If we are maintaining Observe persist */
3720 if (resource == context->unknown_resource) {
3721 context->unknown_pdu = pdu;
3722 context->unknown_session = session;
3723 } else
3724 context->unknown_pdu = NULL;
3725#endif /* COAP_WITH_OBSERVE_PERSIST */
3726
3727 /*
3728 * Call the request handler with everything set up
3729 */
3730 if (resource == &resource_uri_wellknown) {
3731 /* Leave context locked */
3732 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3733 (int)resource->uri_path->length, (int)resource->uri_path->length,
3734 resource->uri_path->s);
3735 h(resource, session, pdu, query, response);
3736 } else {
3737 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3738 (int)resource->uri_path->length, (int)resource->uri_path->length,
3739 resource->uri_path->s);
3741 h(resource, session, pdu, query, response),
3742 /* context is being freed off */
3743 goto finish);
3744 }
3745
3746 /* Check validity of response code */
3747 if (!coap_check_code_class(session, response)) {
3748 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3749 COAP_RESPONSE_CLASS(response->code),
3750 response->code & 0x1f);
3751 goto drop_it_no_debug;
3752 }
3753
3754 /* Check if lg_xmit generated and update PDU code if so */
3755 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3756
3757 if (free_lg_srcv) {
3758 /* Check to see if the server is doing a 4.01 + Echo response */
3759 if (response->code == COAP_RESPONSE_CODE(401) &&
3760 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3761 /* Need to keep lg_srcv around for client's response */
3762 } else {
3763 LL_DELETE(session->lg_srcv, free_lg_srcv);
3764 coap_block_delete_lg_srcv(session, free_lg_srcv);
3765 }
3766 }
3767 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3768 /* Just in case, as there are more to go */
3769 response->code = COAP_RESPONSE_CODE(231);
3770 }
3771
3772skip_handler:
3773 if (send_early_empty_ack &&
3774 response->type == COAP_MESSAGE_ACK) {
3775 /* Response is now separate - convert to CON as needed */
3776 response->type = COAP_MESSAGE_CON;
3777 /* Check for empty ACK - need to drop as already sent */
3778 if (response->code == 0) {
3779 goto drop_it_no_debug;
3780 }
3781 }
3782 respond = no_response(pdu, response, session, resource);
3783 if (respond != RESPONSE_DROP) {
3784#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3785 coap_mid_t mid = pdu->mid;
3786#endif
3787 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3788 if (observe) {
3790 }
3791 }
3792 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3793 if (observe)
3794 coap_delete_observer(resource, session, &pdu->actual_token);
3795 if (response->code != COAP_RESPONSE_CODE(413))
3797 }
3798
3799 /* If original request contained a token, and the registered
3800 * application handler made no changes to the response, then
3801 * this is an empty ACK with a token, which is a malformed
3802 * PDU */
3803 if ((response->type == COAP_MESSAGE_ACK)
3804 && (response->code == 0)) {
3805 /* Remove token from otherwise-empty acknowledgment PDU */
3806 response->actual_token.length = 0;
3807 response->e_token_length = 0;
3808 response->used_size = 0;
3809 response->data = NULL;
3810 }
3811
3812 if (!coap_is_mcast(&session->addr_info.local) ||
3813 (context->mcast_per_resource &&
3814 resource &&
3816 /* No delays to response */
3817#if COAP_Q_BLOCK_SUPPORT
3818 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
3819 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
3820 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
3821 block.m) {
3822 if (coap_send_q_block2(session, resource, query, pdu->code, block,
3823 response,
3824 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
3825 coap_log_debug("cannot send response for mid=0x%x\n", mid);
3826 response = NULL;
3827 if (query)
3828 coap_delete_string(query);
3829 goto finish;
3830 }
3831#endif /* COAP_Q_BLOCK_SUPPORT */
3832 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
3833 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
3834 }
3835 } else {
3836 /* Need to delay mcast response */
3837 coap_queue_t *node = coap_new_node();
3838 uint8_t r;
3839 coap_tick_t delay;
3840
3841 if (!node) {
3842 coap_log_debug("mcast delay: insufficient memory\n");
3843 goto drop_it_no_debug;
3844 }
3845 if (!coap_pdu_encode_header(response, session->proto)) {
3847 goto drop_it_no_debug;
3848 }
3849
3850 node->id = response->mid;
3851 node->pdu = response;
3852 node->is_mcast = 1;
3853 coap_prng_lkd(&r, sizeof(r));
3854 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
3855 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
3856 coap_session_str(session),
3857 response->mid,
3858 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
3859 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
3860 1000 / COAP_TICKS_PER_SECOND));
3861 node->timeout = (unsigned int)delay;
3862 /* Use this to delay transmission */
3863 coap_wait_ack(session->context, session, node);
3864 }
3865 } else {
3866 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
3867 coap_session_str(session),
3868 response->mid);
3869 coap_show_pdu(COAP_LOG_DEBUG, response);
3870drop_it_no_debug:
3871 coap_delete_pdu_lkd(response);
3872 }
3873 if (query)
3874 coap_delete_string(query);
3875#if COAP_Q_BLOCK_SUPPORT
3876 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
3877 if (COAP_PROTO_RELIABLE(session->proto)) {
3878 if (block.m) {
3879 /* All of the sequence not in yet */
3880 goto finish;
3881 }
3882 } else if (pdu->type == COAP_MESSAGE_NON) {
3883 /* More to go and not at a payload break */
3884 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
3885 goto finish;
3886 }
3887 }
3888 }
3889#endif /* COAP_Q_BLOCK_SUPPORT */
3890
3891#if COAP_Q_BLOCK_SUPPORT || COAP_THREAD_SAFE
3892finish:
3893#endif /* COAP_Q_BLOCK_SUPPORT || COAP_THREAD_SAFE */
3894 coap_delete_string(uri_path);
3895 return;
3896
3897fail_response:
3898 coap_delete_pdu_lkd(response);
3899 response =
3901 &opt_filter);
3902 if (response)
3903 goto skip_handler;
3904 coap_delete_string(uri_path);
3905}
3906#endif /* COAP_SERVER_SUPPORT */
3907
3908#if COAP_CLIENT_SUPPORT
3909static void
3910handle_response(coap_context_t *context, coap_session_t *session,
3911 coap_pdu_t *sent, coap_pdu_t *rcvd) {
3912
3913 /* Set in case there is a later call to coap_update_token() */
3914 rcvd->session = session;
3915
3916 /* Check for message duplication */
3917 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
3918 if (rcvd->type == COAP_MESSAGE_CON) {
3919 if (rcvd->mid == session->last_con_mid) {
3920 /* Duplicate response: send ACK/RST, but don't process */
3921 if (session->last_con_handler_res == COAP_RESPONSE_OK)
3922 coap_send_ack_lkd(session, rcvd);
3923 else
3924 coap_send_rst_lkd(session, rcvd);
3925 return;
3926 }
3927 session->last_con_mid = rcvd->mid;
3928 } else if (rcvd->type == COAP_MESSAGE_ACK) {
3929 if (rcvd->mid == session->last_ack_mid) {
3930 /* Duplicate response */
3931 return;
3932 }
3933 session->last_ack_mid = rcvd->mid;
3934 }
3935 }
3936 /* Check to see if checking out extended token support */
3937 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
3938 session->remote_test_mid == rcvd->mid) {
3939
3940 if (rcvd->actual_token.length != session->max_token_size ||
3941 rcvd->code == COAP_RESPONSE_CODE(400) ||
3942 rcvd->code == COAP_RESPONSE_CODE(503)) {
3943 coap_log_debug("Extended Token requested size support not available\n");
3945 } else {
3946 coap_log_debug("Extended Token support available\n");
3947 }
3949 session->doing_first = 0;
3950 return;
3951 }
3952#if COAP_Q_BLOCK_SUPPORT
3953 /* Check to see if checking out Q-Block support */
3954 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
3955 session->remote_test_mid == rcvd->mid) {
3956 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
3957 coap_log_debug("Q-Block support not available\n");
3958 set_block_mode_drop_q(session->block_mode);
3959 } else {
3960 coap_block_b_t qblock;
3961
3962 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
3963 coap_log_debug("Q-Block support available\n");
3964 set_block_mode_has_q(session->block_mode);
3965 } else {
3966 coap_log_debug("Q-Block support not available\n");
3967 set_block_mode_drop_q(session->block_mode);
3968 }
3969 }
3970 session->doing_first = 0;
3971 return;
3972 }
3973#endif /* COAP_Q_BLOCK_SUPPORT */
3974
3975 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3976 /* See if need to send next block to server */
3977 if (coap_handle_response_send_block(session, sent, rcvd)) {
3978 /* Next block transmitted, no need to inform app */
3979 coap_send_ack_lkd(session, rcvd);
3980 return;
3981 }
3982
3983 /* Need to see if needing to request next block */
3984 if (coap_handle_response_get_block(context, session, sent, rcvd,
3985 COAP_RECURSE_OK)) {
3986 /* Next block transmitted, ack sent no need to inform app */
3987 return;
3988 }
3989 }
3990 if (session->doing_first)
3991 session->doing_first = 0;
3992
3993 /* Call application-specific response handler when available. */
3994 if (session->doing_send_recv && session->req_token &&
3995 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
3996 /* processing coap_send_recv() call */
3997 session->resp_pdu = rcvd;
3999 coap_send_ack_lkd(session, rcvd);
4001 } else if (context->response_handler) {
4002 coap_response_t ret;
4003
4004 coap_lock_callback_ret_release(ret, context,
4005 context->response_handler(session, sent, rcvd,
4006 rcvd->mid),
4007 /* context is being freed off */
4008 return);
4009 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4010 coap_send_rst_lkd(session, rcvd);
4012 } else {
4013 coap_send_ack_lkd(session, rcvd);
4015 }
4016 } else {
4017 coap_send_ack_lkd(session, rcvd);
4019 }
4020}
4021#endif /* COAP_CLIENT_SUPPORT */
4022
4023#if !COAP_DISABLE_TCP
4024static void
4026 coap_pdu_t *pdu) {
4027 coap_opt_iterator_t opt_iter;
4028 coap_opt_t *option;
4029 int set_mtu = 0;
4030
4031 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4032
4033 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4034 if (session->csm_not_seen) {
4035 coap_tick_t now;
4036
4037 coap_ticks(&now);
4038 /* CSM timeout before CSM seen */
4039 coap_log_warn("***%s: CSM received after CSM timeout\n",
4040 coap_session_str(session));
4041 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4042 coap_session_str(session),
4043 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4044 }
4045 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4047 }
4048 while ((option = coap_option_next(&opt_iter))) {
4051 coap_opt_length(option)));
4052 set_mtu = 1;
4053 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4054 session->csm_block_supported = 1;
4055 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4056 session->max_token_size =
4058 coap_opt_length(option));
4061 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4064 }
4065 }
4066 if (set_mtu) {
4067 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4068 session->csm_bert_rem_support = 1;
4069 else
4070 session->csm_bert_rem_support = 0;
4071 }
4072 if (session->state == COAP_SESSION_STATE_CSM)
4073 coap_session_connected(session);
4074 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4076 if (context->ping_handler) {
4077 coap_lock_callback(context,
4078 context->ping_handler(session, pdu, pdu->mid));
4079 }
4080 if (pong) {
4082 coap_send_internal(session, pong, NULL);
4083 }
4084 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4085 session->last_pong = session->last_rx_tx;
4086 if (context->pong_handler) {
4087 coap_lock_callback(context,
4088 context->pong_handler(session, pdu, pdu->mid));
4089 }
4090 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4091 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4093 }
4094}
4095#endif /* !COAP_DISABLE_TCP */
4096
4097static int
4099 if (COAP_PDU_IS_REQUEST(pdu) &&
4100 pdu->actual_token.length >
4101 (session->type == COAP_SESSION_TYPE_CLIENT ?
4102 session->max_token_size : session->context->max_token_size)) {
4103 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4104 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4105 coap_opt_filter_t opt_filter;
4106 coap_pdu_t *response;
4107
4108 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4109 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4110 &opt_filter);
4111 if (!response) {
4112 coap_log_warn("coap_dispatch: cannot create error response\n");
4113 } else {
4114 /*
4115 * Note - have to leave in oversize token as per
4116 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4117 */
4118 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4119 coap_log_warn("coap_dispatch: error sending response\n");
4120 }
4121 } else {
4122 /* Indicate no extended token support */
4123 coap_send_rst_lkd(session, pdu);
4124 }
4125 return 0;
4126 }
4127 return 1;
4128}
4129
4130void
4132 coap_pdu_t *pdu) {
4133 coap_queue_t *sent = NULL;
4134 coap_pdu_t *response;
4135 coap_pdu_t *orig_pdu = NULL;
4136 coap_opt_filter_t opt_filter;
4137 int is_ping_rst;
4138 int packet_is_bad = 0;
4139#if COAP_OSCORE_SUPPORT
4140 coap_opt_iterator_t opt_iter;
4141 coap_pdu_t *dec_pdu = NULL;
4142#endif /* COAP_OSCORE_SUPPORT */
4143 int is_ext_token_rst;
4144
4145 pdu->session = session;
4147
4148 /* Check validity of received code */
4149 if (!coap_check_code_class(session, pdu)) {
4150 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4152 pdu->code & 0x1f);
4153 packet_is_bad = 1;
4154 if (pdu->type == COAP_MESSAGE_CON) {
4156 }
4157 /* find message id in sendqueue to stop retransmission */
4158 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4159 goto cleanup;
4160 }
4161
4162 coap_option_filter_clear(&opt_filter);
4163
4164#if COAP_SERVER_SUPPORT
4165 /* See if this a repeat request */
4166 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4168 coap_digest_t digest;
4169
4170 coap_pdu_cksum(pdu, &digest);
4171 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4172#if COAP_OSCORE_SUPPORT
4173 uint8_t oscore_encryption = session->oscore_encryption;
4174
4175 session->oscore_encryption = 0;
4176#endif /* COAP_OSCORE_SUPPORT */
4177 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4178 cached_pdu must not be removed */
4180 coap_log_debug("Retransmit response to duplicate request\n");
4181 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4182#if COAP_OSCORE_SUPPORT
4183 session->oscore_encryption = oscore_encryption;
4184#endif /* COAP_OSCORE_SUPPORT */
4185 return;
4186 }
4187#if COAP_OSCORE_SUPPORT
4188 session->oscore_encryption = oscore_encryption;
4189#endif /* COAP_OSCORE_SUPPORT */
4190 }
4191 }
4192#endif /* COAP_SERVER_SUPPORT */
4193#if COAP_OSCORE_SUPPORT
4194 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4195 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4196 if (pdu->type == COAP_MESSAGE_NON) {
4197 coap_send_rst_lkd(session, pdu);
4198 goto cleanup;
4199 } else if (pdu->type == COAP_MESSAGE_CON) {
4200 if (COAP_PDU_IS_REQUEST(pdu)) {
4201 response =
4202 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4203
4204 if (!response) {
4205 coap_log_warn("coap_dispatch: cannot create error response\n");
4206 } else {
4207 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4208 coap_log_warn("coap_dispatch: error sending response\n");
4209 }
4210 } else {
4211 coap_send_rst_lkd(session, pdu);
4212 }
4213 }
4214 goto cleanup;
4215 }
4216
4217 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4218 int decrypt = 1;
4219#if COAP_SERVER_SUPPORT
4220 coap_opt_t *opt;
4221 coap_resource_t *resource;
4222 coap_uri_t uri;
4223#endif /* COAP_SERVER_SUPPORT */
4224
4225 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4226 decrypt = 0;
4227
4228#if COAP_SERVER_SUPPORT
4229 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4230 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4231 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4232 != NULL) {
4233 /* Need to check whether this is a direct or proxy session */
4234 memset(&uri, 0, sizeof(uri));
4235 uri.host.length = coap_opt_length(opt);
4236 uri.host.s = coap_opt_value(opt);
4237 resource = context->proxy_uri_resource;
4238 if (uri.host.length && resource && resource->proxy_name_count &&
4239 resource->proxy_name_list) {
4240 size_t i;
4241 for (i = 0; i < resource->proxy_name_count; i++) {
4242 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4243 break;
4244 }
4245 }
4246 if (i == resource->proxy_name_count) {
4247 /* This server is not hosting the proxy connection endpoint */
4248 decrypt = 0;
4249 }
4250 }
4251 }
4252#endif /* COAP_SERVER_SUPPORT */
4253 if (decrypt) {
4254 /* find message id in sendqueue to stop retransmission and get sent */
4255 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4256 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4257 orig_pdu = pdu;
4258 coap_pdu_reference_lkd(orig_pdu);
4259 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4260 if (session->recipient_ctx == NULL ||
4261 session->recipient_ctx->initial_state == 0) {
4262 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4263 }
4265 coap_delete_pdu_lkd(orig_pdu);
4266 return;
4267 } else {
4268 session->oscore_encryption = 1;
4269 pdu = dec_pdu;
4270 }
4271 coap_log_debug("Decrypted PDU\n");
4273 }
4274 }
4275#endif /* COAP_OSCORE_SUPPORT */
4276
4277 switch (pdu->type) {
4278 case COAP_MESSAGE_ACK:
4279 /* find message id in sendqueue to stop retransmission */
4280 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4281
4282 if (sent && session->con_active) {
4283 session->con_active--;
4284 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4285 /* Flush out any entries on session->delayqueue */
4286 coap_session_connected(session);
4287 }
4288 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4289 packet_is_bad = 1;
4290 goto cleanup;
4291 }
4292
4293#if COAP_SERVER_SUPPORT
4294 /* if sent code was >= 64 the message might have been a
4295 * notification. Then, we must flag the observer to be alive
4296 * by setting obs->fail_cnt = 0. */
4297 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4298 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4299 }
4300#endif /* COAP_SERVER_SUPPORT */
4301
4302 if (pdu->code == 0) {
4303#if COAP_Q_BLOCK_SUPPORT
4304 if (sent) {
4305 coap_block_b_t block;
4306
4307 if (sent->pdu->type == COAP_MESSAGE_CON &&
4308 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4309 coap_get_block_b(session, sent->pdu,
4310 COAP_PDU_IS_REQUEST(sent->pdu) ?
4312 &block)) {
4313 if (block.m) {
4314#if COAP_CLIENT_SUPPORT
4315 if (COAP_PDU_IS_REQUEST(sent->pdu))
4316 coap_send_q_block1(session, block, sent->pdu,
4317 COAP_SEND_SKIP_PDU);
4318#endif /* COAP_CLIENT_SUPPORT */
4319 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4320 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4321 sent->pdu, COAP_SEND_SKIP_PDU);
4322 }
4323 }
4324 }
4325#endif /* COAP_Q_BLOCK_SUPPORT */
4326#if COAP_CLIENT_SUPPORT
4327 /*
4328 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4329 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4330 * response if the response was piggy-backed. Here, a separate response
4331 * detected and so the lg_crcv needs to be set up before the sent PDU
4332 * information is lost.
4333 *
4334 * lg_crcv was not set up if not a CoAP request or if DELETE.
4335 *
4336 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4337 * options.
4338 */
4339 if (sent &&
4340 !coap_check_send_need_lg_crcv(session, pdu) &&
4341 COAP_PDU_IS_REQUEST(sent->pdu)) {
4342 /*
4343 * lg_crcv was not set up in coap_send(). It could have been set up
4344 * the first separate response.
4345 * See if there already is a lg_crcv set up.
4346 */
4347 coap_lg_crcv_t *lg_crcv;
4348 uint64_t token_match =
4350 sent->pdu->actual_token.length));
4351
4352 LL_FOREACH(session->lg_crcv, lg_crcv) {
4353 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4354 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4355 break;
4356 }
4357 }
4358 if (!lg_crcv) {
4359 /*
4360 * Need to set up a lg_crcv as it was not set up in coap_send()
4361 * to save time, but server has not sent back a piggy-back response.
4362 */
4363 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4364 if (lg_crcv) {
4365 LL_PREPEND(session->lg_crcv, lg_crcv);
4366 }
4367 }
4368 }
4369#endif /* COAP_CLIENT_SUPPORT */
4370 /* an empty ACK needs no further handling */
4371 goto cleanup;
4372 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4373 /* This is not legitimate - Request using ACK - ignore */
4374 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4376 pdu->code & 0x1f);
4377 packet_is_bad = 1;
4378 goto cleanup;
4379 }
4380
4381 break;
4382
4383 case COAP_MESSAGE_RST:
4384 /* We have sent something the receiver disliked, so we remove
4385 * not only the message id but also the subscriptions we might
4386 * have. */
4387 is_ping_rst = 0;
4388 if (pdu->mid == session->last_ping_mid &&
4389 context->ping_timeout && session->last_ping > 0)
4390 is_ping_rst = 1;
4391
4392#if COAP_Q_BLOCK_SUPPORT
4393 /* Check to see if checking out Q-Block support */
4394 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4395 session->remote_test_mid == pdu->mid) {
4396 coap_log_debug("Q-Block support not available\n");
4397 set_block_mode_drop_q(session->block_mode);
4398 }
4399#endif /* COAP_Q_BLOCK_SUPPORT */
4400
4401 /* Check to see if checking out extended token support */
4402 is_ext_token_rst = 0;
4403 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4404 session->remote_test_mid == pdu->mid) {
4405 coap_log_debug("Extended Token support not available\n");
4408 session->doing_first = 0;
4409 is_ext_token_rst = 1;
4410 }
4411
4412 if (!is_ping_rst && !is_ext_token_rst)
4413 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4414
4415 if (session->con_active) {
4416 session->con_active--;
4417 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4418 /* Flush out any entries on session->delayqueue */
4419 coap_session_connected(session);
4420 }
4421
4422 /* find message id in sendqueue to stop retransmission */
4423 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4424
4425 if (sent) {
4426 if (!is_ping_rst)
4427 coap_cancel(context, sent);
4428
4429 if (!is_ping_rst && !is_ext_token_rst) {
4430 if (sent->pdu->type==COAP_MESSAGE_CON) {
4431 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4432 }
4433 } else if (is_ping_rst) {
4434 if (context->pong_handler) {
4435 coap_lock_callback(context,
4436 context->pong_handler(session, pdu, pdu->mid));
4437 }
4438 session->last_pong = session->last_rx_tx;
4440 }
4441 } else {
4442#if COAP_SERVER_SUPPORT
4443 /* Need to check is there is a subscription active and delete it */
4444 RESOURCES_ITER(context->resources, r) {
4445 coap_subscription_t *obs, *tmp;
4446 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4447 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4448 /* Need to do this now as session may get de-referenced */
4450 coap_delete_observer(r, session, &obs->pdu->actual_token);
4451 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4452 coap_session_release_lkd(session);
4453 goto cleanup;
4454 }
4455 }
4456 }
4457#endif /* COAP_SERVER_SUPPORT */
4458 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4459 }
4460 goto cleanup;
4461
4462 case COAP_MESSAGE_NON:
4463 /* check for unknown critical options */
4464 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4465 packet_is_bad = 1;
4466 coap_send_rst_lkd(session, pdu);
4467 goto cleanup;
4468 }
4469 if (!check_token_size(session, pdu)) {
4470 goto cleanup;
4471 }
4472 break;
4473
4474 case COAP_MESSAGE_CON: /* check for unknown critical options */
4475 /* In a lossy context, the ACK of a separate response may have
4476 * been lost, so we need to stop retransmitting requests with the
4477 * same token. Matching on token potentially containing ext length bytes.
4478 */
4479 /* find message token in sendqueue to stop retransmission */
4480 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4481
4482 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4483 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4484 packet_is_bad = 1;
4485 if (COAP_PDU_IS_REQUEST(pdu)) {
4486 response =
4487 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4488
4489 if (!response) {
4490 coap_log_warn("coap_dispatch: cannot create error response\n");
4491 } else {
4492 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4493 coap_log_warn("coap_dispatch: error sending response\n");
4494 }
4495 } else {
4496 coap_send_rst_lkd(session, pdu);
4497 }
4498 goto cleanup;
4499 }
4500 if (!check_token_size(session, pdu)) {
4501 goto cleanup;
4502 }
4503 break;
4504 default:
4505 break;
4506 }
4507
4508 /* Pass message to upper layer if a specific handler was
4509 * registered for a request that should be handled locally. */
4510#if !COAP_DISABLE_TCP
4511 if (COAP_PDU_IS_SIGNALING(pdu))
4512 handle_signaling(context, session, pdu);
4513 else
4514#endif /* !COAP_DISABLE_TCP */
4515#if COAP_SERVER_SUPPORT
4516 if (COAP_PDU_IS_REQUEST(pdu))
4517 handle_request(context, session, pdu, orig_pdu);
4518 else
4519#endif /* COAP_SERVER_SUPPORT */
4520#if COAP_CLIENT_SUPPORT
4521 if (COAP_PDU_IS_RESPONSE(pdu))
4522 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4523 else
4524#endif /* COAP_CLIENT_SUPPORT */
4525 {
4526 if (COAP_PDU_IS_EMPTY(pdu)) {
4527 if (context->ping_handler) {
4528 coap_lock_callback(context,
4529 context->ping_handler(session, pdu, pdu->mid));
4530 }
4531 } else {
4532 packet_is_bad = 1;
4533 }
4534 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4536 pdu->code & 0x1f);
4537
4538 if (!coap_is_mcast(&session->addr_info.local)) {
4539 if (COAP_PDU_IS_EMPTY(pdu)) {
4540 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4541 coap_tick_t now;
4542 coap_ticks(&now);
4543 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4545 session->last_tx_rst = now;
4546 }
4547 }
4548 } else {
4549 if (pdu->type == COAP_MESSAGE_CON)
4551 }
4552 }
4553 }
4554
4555cleanup:
4556 if (packet_is_bad) {
4557 if (sent) {
4558 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4559 } else {
4561 }
4562 }
4563 coap_delete_pdu_lkd(orig_pdu);
4565#if COAP_OSCORE_SUPPORT
4566 coap_delete_pdu_lkd(dec_pdu);
4567#endif /* COAP_OSCORE_SUPPORT */
4568}
4569
4570#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4571static const char *
4573 switch (event) {
4575 return "COAP_EVENT_DTLS_CLOSED";
4577 return "COAP_EVENT_DTLS_CONNECTED";
4579 return "COAP_EVENT_DTLS_RENEGOTIATE";
4581 return "COAP_EVENT_DTLS_ERROR";
4583 return "COAP_EVENT_TCP_CONNECTED";
4585 return "COAP_EVENT_TCP_CLOSED";
4587 return "COAP_EVENT_TCP_FAILED";
4589 return "COAP_EVENT_SESSION_CONNECTED";
4591 return "COAP_EVENT_SESSION_CLOSED";
4593 return "COAP_EVENT_SESSION_FAILED";
4595 return "COAP_EVENT_PARTIAL_BLOCK";
4597 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4599 return "COAP_EVENT_SERVER_SESSION_NEW";
4601 return "COAP_EVENT_SERVER_SESSION_DEL";
4603 return "COAP_EVENT_BAD_PACKET";
4605 return "COAP_EVENT_MSG_RETRANSMITTED";
4607 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4609 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4611 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4613 return "COAP_EVENT_OSCORE_NO_SECURITY";
4615 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4617 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4619 return "COAP_EVENT_WS_PACKET_SIZE";
4621 return "COAP_EVENT_WS_CONNECTED";
4623 return "COAP_EVENT_WS_CLOSED";
4625 return "COAP_EVENT_KEEPALIVE_FAILURE";
4626 default:
4627 return "???";
4628 }
4629}
4630#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4631
4632COAP_API int
4634 coap_session_t *session) {
4635 int ret;
4636
4637 coap_lock_lock(context, return 0);
4638 ret = coap_handle_event_lkd(context, event, session);
4639 coap_lock_unlock(context);
4640 return ret;
4641}
4642
4643int
4645 coap_session_t *session) {
4646 int ret = 0;
4647
4648 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4649
4650 if (context->handle_event) {
4651 coap_lock_callback_ret(ret, context, context->handle_event(session, event));
4652#if COAP_PROXY_SUPPORT
4653 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4655#endif /* COAP_PROXY_SUPPORT */
4656#if COAP_CLIENT_SUPPORT
4657 switch (event) {
4670 /* Those that are deemed fatal to end sending a request */
4671 session->doing_send_recv = 0;
4672 break;
4687 default:
4688 break;
4689 }
4690#endif /* COAP_CLIENT_SUPPORT */
4691 }
4692 return ret;
4693}
4694
4695COAP_API int
4697 int ret;
4698
4699 coap_lock_lock(context, return 0);
4700 ret = coap_can_exit_lkd(context);
4701 coap_lock_unlock(context);
4702 return ret;
4703}
4704
4705int
4707 coap_session_t *s, *rtmp;
4708 if (!context)
4709 return 1;
4710 coap_lock_check_locked(context);
4711 if (context->sendqueue)
4712 return 0;
4713#if COAP_SERVER_SUPPORT
4714 coap_endpoint_t *ep;
4715
4716 LL_FOREACH(context->endpoint, ep) {
4717 SESSIONS_ITER(ep->sessions, s, rtmp) {
4718 if (s->delayqueue)
4719 return 0;
4720 if (s->lg_xmit)
4721 return 0;
4722 }
4723 }
4724#endif /* COAP_SERVER_SUPPORT */
4725#if COAP_CLIENT_SUPPORT
4726 SESSIONS_ITER(context->sessions, s, rtmp) {
4727 if (s->delayqueue)
4728 return 0;
4729 if (s->lg_xmit)
4730 return 0;
4731 }
4732#endif /* COAP_CLIENT_SUPPORT */
4733 return 1;
4734}
4735#if COAP_SERVER_SUPPORT
4736#if COAP_ASYNC_SUPPORT
4738coap_check_async(coap_context_t *context, coap_tick_t now) {
4739 coap_tick_t next_due = 0;
4740 coap_async_t *async, *tmp;
4741
4742 LL_FOREACH_SAFE(context->async_state, async, tmp) {
4743 if (async->delay != 0 && async->delay <= now) {
4744 /* Send off the request to the application */
4745 coap_log_debug("Async PDU presented to app.\n");
4746 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
4747 handle_request(context, async->session, async->pdu, NULL);
4748
4749 /* Remove this async entry as it has now fired */
4750 coap_free_async_lkd(async->session, async);
4751 } else {
4752 if (next_due == 0 || next_due > async->delay - now)
4753 next_due = async->delay - now;
4754 }
4755 }
4756 return next_due;
4757}
4758#endif /* COAP_ASYNC_SUPPORT */
4759#endif /* COAP_SERVER_SUPPORT */
4760
4762
4763#if COAP_THREAD_SAFE
4764/*
4765 * Global lock for multi-thread support
4766 */
4767coap_lock_t global_lock;
4768#endif /* COAP_THREAD_SAFE */
4769
4770void
4772 coap_tick_t now;
4773#ifndef WITH_CONTIKI
4774 uint64_t us;
4775#endif /* !WITH_CONTIKI */
4776
4777 if (coap_started)
4778 return;
4779 coap_started = 1;
4780
4781#if COAP_THREAD_SAFE
4783#endif /* COAP_THREAD_SAFE */
4784
4785#if defined(HAVE_WINSOCK2_H)
4786 WORD wVersionRequested = MAKEWORD(2, 2);
4787 WSADATA wsaData;
4788 WSAStartup(wVersionRequested, &wsaData);
4789#endif
4791 coap_ticks(&now);
4792#ifndef WITH_CONTIKI
4793 us = coap_ticks_to_rt_us(now);
4794 /* Be accurate to the nearest (approx) us */
4795 coap_prng_init_lkd((unsigned int)us);
4796#else /* WITH_CONTIKI */
4797 coap_start_io_process();
4798#endif /* WITH_CONTIKI */
4801#ifdef WITH_LWIP
4802 coap_io_lwip_init();
4803#endif /* WITH_LWIP */
4804#if COAP_SERVER_SUPPORT
4805 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
4806 (const uint8_t *)".well-known/core"
4807 };
4808 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
4809 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
4810 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
4811 resource_uri_wellknown.uri_path = &well_known;
4812#endif /* COAP_SERVER_SUPPORT */
4814}
4815
4816void
4818 if (!coap_started)
4819 return;
4820 coap_started = 0;
4821#if defined(HAVE_WINSOCK2_H)
4822 WSACleanup();
4823#elif defined(WITH_CONTIKI)
4824 coap_stop_io_process();
4825#endif
4826#ifdef WITH_LWIP
4827 coap_io_lwip_cleanup();
4828#endif /* WITH_LWIP */
4830
4832}
4833
4834void
4836 coap_response_handler_t handler) {
4837#if COAP_CLIENT_SUPPORT
4838 context->response_handler = handler;
4839#else /* ! COAP_CLIENT_SUPPORT */
4840 (void)context;
4841 (void)handler;
4842#endif /* COAP_CLIENT_SUPPORT */
4843}
4844
4845void
4847 coap_nack_handler_t handler) {
4848 context->nack_handler = handler;
4849}
4850
4851void
4853 coap_ping_handler_t handler) {
4854 context->ping_handler = handler;
4855}
4856
4857void
4859 coap_pong_handler_t handler) {
4860 context->pong_handler = handler;
4861}
4862
4863COAP_API void
4865 coap_lock_lock(ctx, return);
4866 coap_register_option_lkd(ctx, type);
4867 coap_lock_unlock(ctx);
4868}
4869
4870void
4873}
4874
4875#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
4876#if COAP_SERVER_SUPPORT
4877COAP_API int
4878coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
4879 const char *ifname) {
4880 int ret;
4881
4882 coap_lock_lock(ctx, return -1);
4883 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
4884 coap_lock_unlock(ctx);
4885 return ret;
4886}
4887
4888int
4889coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
4890 const char *ifname) {
4891#if COAP_IPV4_SUPPORT
4892 struct ip_mreq mreq4;
4893#endif /* COAP_IPV4_SUPPORT */
4894#if COAP_IPV6_SUPPORT
4895 struct ipv6_mreq mreq6;
4896#endif /* COAP_IPV6_SUPPORT */
4897 struct addrinfo *resmulti = NULL, hints, *ainfo;
4898 int result = -1;
4899 coap_endpoint_t *endpoint;
4900 int mgroup_setup = 0;
4901
4902 /* Need to have at least one endpoint! */
4903 assert(ctx->endpoint);
4904 if (!ctx->endpoint)
4905 return -1;
4906
4907 /* Default is let the kernel choose */
4908#if COAP_IPV6_SUPPORT
4909 mreq6.ipv6mr_interface = 0;
4910#endif /* COAP_IPV6_SUPPORT */
4911#if COAP_IPV4_SUPPORT
4912 mreq4.imr_interface.s_addr = INADDR_ANY;
4913#endif /* COAP_IPV4_SUPPORT */
4914
4915 memset(&hints, 0, sizeof(hints));
4916 hints.ai_socktype = SOCK_DGRAM;
4917
4918 /* resolve the multicast group address */
4919 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
4920
4921 if (result != 0) {
4922 coap_log_err("coap_join_mcast_group_intf: %s: "
4923 "Cannot resolve multicast address: %s\n",
4924 group_name, gai_strerror(result));
4925 goto finish;
4926 }
4927
4928 /* Need to do a windows equivalent at some point */
4929#ifndef _WIN32
4930 if (ifname) {
4931 /* interface specified - check if we have correct IPv4/IPv6 information */
4932 int done_ip4 = 0;
4933 int done_ip6 = 0;
4934#if defined(ESPIDF_VERSION)
4935 struct netif *netif;
4936#else /* !ESPIDF_VERSION */
4937#if COAP_IPV4_SUPPORT
4938 int ip4fd;
4939#endif /* COAP_IPV4_SUPPORT */
4940 struct ifreq ifr;
4941#endif /* !ESPIDF_VERSION */
4942
4943 /* See which mcast address family types are being asked for */
4944 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
4945 ainfo = ainfo->ai_next) {
4946 switch (ainfo->ai_family) {
4947#if COAP_IPV6_SUPPORT
4948 case AF_INET6:
4949 if (done_ip6)
4950 break;
4951 done_ip6 = 1;
4952#if defined(ESPIDF_VERSION)
4953 netif = netif_find(ifname);
4954 if (netif)
4955 mreq6.ipv6mr_interface = netif_get_index(netif);
4956 else
4957 coap_log_err("coap_join_mcast_group_intf: %s: "
4958 "Cannot get IPv4 address: %s\n",
4959 ifname, coap_socket_strerror());
4960#else /* !ESPIDF_VERSION */
4961 memset(&ifr, 0, sizeof(ifr));
4962 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4963 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4964
4965#ifdef HAVE_IF_NAMETOINDEX
4966 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
4967 if (mreq6.ipv6mr_interface == 0) {
4968 coap_log_warn("coap_join_mcast_group_intf: "
4969 "cannot get interface index for '%s'\n",
4970 ifname);
4971 }
4972#elif defined(__QNXNTO__)
4973#else /* !HAVE_IF_NAMETOINDEX */
4974 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
4975 if (result != 0) {
4976 coap_log_warn("coap_join_mcast_group_intf: "
4977 "cannot get interface index for '%s': %s\n",
4978 ifname, coap_socket_strerror());
4979 } else {
4980 /* Capture the IPv6 if_index for later */
4981 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
4982 }
4983#endif /* !HAVE_IF_NAMETOINDEX */
4984#endif /* !ESPIDF_VERSION */
4985#endif /* COAP_IPV6_SUPPORT */
4986 break;
4987#if COAP_IPV4_SUPPORT
4988 case AF_INET:
4989 if (done_ip4)
4990 break;
4991 done_ip4 = 1;
4992#if defined(ESPIDF_VERSION)
4993 netif = netif_find(ifname);
4994 if (netif)
4995 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
4996 else
4997 coap_log_err("coap_join_mcast_group_intf: %s: "
4998 "Cannot get IPv4 address: %s\n",
4999 ifname, coap_socket_strerror());
5000#else /* !ESPIDF_VERSION */
5001 /*
5002 * Need an AF_INET socket to do this unfortunately to stop
5003 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5004 */
5005 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5006 if (ip4fd == -1) {
5007 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5008 ifname, coap_socket_strerror());
5009 continue;
5010 }
5011 memset(&ifr, 0, sizeof(ifr));
5012 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5013 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5014 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5015 if (result != 0) {
5016 coap_log_err("coap_join_mcast_group_intf: %s: "
5017 "Cannot get IPv4 address: %s\n",
5018 ifname, coap_socket_strerror());
5019 } else {
5020 /* Capture the IPv4 address for later */
5021 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5022 }
5023 close(ip4fd);
5024#endif /* !ESPIDF_VERSION */
5025 break;
5026#endif /* COAP_IPV4_SUPPORT */
5027 default:
5028 break;
5029 }
5030 }
5031 }
5032#else /* _WIN32 */
5033 /*
5034 * On Windows this function ignores the ifname variable so we unset this
5035 * variable on this platform in any case in order to enable the interface
5036 * selection from the bind address below.
5037 */
5038 ifname = 0;
5039#endif /* _WIN32 */
5040
5041 /* Add in mcast address(es) to appropriate interface */
5042 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5043 LL_FOREACH(ctx->endpoint, endpoint) {
5044 /* Only UDP currently supported */
5045 if (endpoint->proto == COAP_PROTO_UDP) {
5046 coap_address_t gaddr;
5047
5048 coap_address_init(&gaddr);
5049#if COAP_IPV6_SUPPORT
5050 if (ainfo->ai_family == AF_INET6) {
5051 if (!ifname) {
5052 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5053 /*
5054 * Do it on the ifindex that the server is listening on
5055 * (sin6_scope_id could still be 0)
5056 */
5057 mreq6.ipv6mr_interface =
5058 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5059 } else {
5060 mreq6.ipv6mr_interface = 0;
5061 }
5062 }
5063 gaddr.addr.sin6.sin6_family = AF_INET6;
5064 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5065 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5066 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5067 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5068 (char *)&mreq6, sizeof(mreq6));
5069 }
5070#endif /* COAP_IPV6_SUPPORT */
5071#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5072 else
5073#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5074#if COAP_IPV4_SUPPORT
5075 if (ainfo->ai_family == AF_INET) {
5076 if (!ifname) {
5077 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5078 /*
5079 * Do it on the interface that the server is listening on
5080 * (sin_addr could still be INADDR_ANY)
5081 */
5082 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5083 } else {
5084 mreq4.imr_interface.s_addr = INADDR_ANY;
5085 }
5086 }
5087 gaddr.addr.sin.sin_family = AF_INET;
5088 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5089 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5090 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5091 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5092 (char *)&mreq4, sizeof(mreq4));
5093 }
5094#endif /* COAP_IPV4_SUPPORT */
5095 else {
5096 continue;
5097 }
5098
5099 if (result == COAP_SOCKET_ERROR) {
5100 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5101 group_name, coap_socket_strerror());
5102 } else {
5103 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5104
5105 addr_str[sizeof(addr_str)-1] = '\000';
5106 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5107 sizeof(addr_str) - 1)) {
5108 if (ifname)
5109 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5110 ifname);
5111 else
5112 coap_log_debug("added mcast group %s\n", addr_str);
5113 }
5114 mgroup_setup = 1;
5115 }
5116 }
5117 }
5118 }
5119 if (!mgroup_setup) {
5120 result = -1;
5121 }
5122
5123finish:
5124 freeaddrinfo(resmulti);
5125
5126 return result;
5127}
5128
5129void
5131 context->mcast_per_resource = 1;
5132}
5133
5134#endif /* ! COAP_SERVER_SUPPORT */
5135
5136#if COAP_CLIENT_SUPPORT
5137int
5138coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5139 if (session && coap_is_mcast(&session->addr_info.remote)) {
5140 switch (session->addr_info.remote.addr.sa.sa_family) {
5141#if COAP_IPV4_SUPPORT
5142 case AF_INET:
5143 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5144 (const char *)&hops, sizeof(hops)) < 0) {
5145 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5146 hops, coap_socket_strerror());
5147 return 0;
5148 }
5149 return 1;
5150#endif /* COAP_IPV4_SUPPORT */
5151#if COAP_IPV6_SUPPORT
5152 case AF_INET6:
5153 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5154 (const char *)&hops, sizeof(hops)) < 0) {
5155 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5156 hops, coap_socket_strerror());
5157 return 0;
5158 }
5159 return 1;
5160#endif /* COAP_IPV6_SUPPORT */
5161 default:
5162 break;
5163 }
5164 }
5165 return 0;
5166}
5167#endif /* COAP_CLIENT_SUPPORT */
5168
5169#else /* defined WITH_CONTIKI || defined WITH_LWIP */
5170COAP_API int
5172 const char *group_name COAP_UNUSED,
5173 const char *ifname COAP_UNUSED) {
5174 return -1;
5175}
5176
5177int
5179 size_t hops COAP_UNUSED) {
5180 return 0;
5181}
5182
5183void
5185}
5186#endif /* defined WITH_CONTIKI || defined WITH_LWIP */
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
void coap_debug_reset(void)
Reset all the defined logging parameters.
#define INET6_ADDRSTRLEN
Definition coap_debug.c:232
#define COAP_Q_BLOCK_SUPPORT
#define COAP_OSCORE_SUPPORT
struct coap_async_t coap_async_t
Async Entry information.
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:2073
void coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length)
Given a packet, set msg and msg_len to an address and length of the packet's data in memory.
Definition coap_io.c:1016
void coap_update_io_timer(coap_context_t *context, coap_tick_t delay)
Update when to continue with I/O processing, unless packets come in in the meantime.
Definition coap_io.c:504
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:29
#define COAP_SOCKET_ERROR
Definition coap_io.h:49
coap_nack_reason_t
Definition coap_io.h:62
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:64
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:63
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:67
@ COAP_NACK_RST
Definition coap_io.h:65
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:68
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
#define COAP_SOCKET_BOUND
the socket is bound
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
void coap_epoll_ctl_mod(coap_socket_t *sock, uint32_t events, const char *func)
Epoll specific function to modify the state of events that epoll is tracking on the appropriate file ...
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
#define COAP_SOCKET_CONNECTED
the socket is connected
@ COAP_LAYER_SESSION
Library specific build wrapper for coap_internal.h.
#define COAP_API
void coap_dump_memory_type_counts(coap_log_t level)
Dumps the current usage of malloc'd memory types.
Definition coap_mem.c:670
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:43
@ COAP_CONTEXT
Definition coap_mem.h:44
@ COAP_STRING
Definition coap_mem.h:39
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
CoAP mutex mechanism wrapper.
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:80
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1014
static int send_recv_terminate
Definition coap_net.c:1955
static int coap_remove_from_queue_token(coap_queue_t **queue, coap_session_t *session, coap_bin_const_t *token, coap_queue_t **node)
Definition coap_net.c:2773
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition coap_net.c:86
void coap_cleanup(void)
Definition coap_net.c:4817
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session's 'ack_timeout'
Definition coap_net.c:101
static const char * coap_event_name(coap_event_t event)
Definition coap_net.c:4572
static int coap_cancel(coap_context_t *context, const coap_queue_t *sent)
This function cancels outstanding messages for the session and token specified in sent.
Definition coap_net.c:3121
int coap_started
Definition coap_net.c:4761
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2208
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2249
COAP_STATIC_INLINE void coap_free_node(coap_queue_t *node)
Definition coap_net.c:111
#define SHR_FP(val, frac)
static void handle_signaling(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition coap_net.c:4025
#define min(a, b)
Definition coap_net.c:73
void coap_startup(void)
Definition coap_net.c:4771
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4098
static unsigned int s_csm_timeout
Definition coap_net.c:503
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition coap_net.c:106
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:97
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:108
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:238
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition coap_notls.c:116
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:181
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:176
uint16_t coap_option_num_t
Definition coap_option.h:20
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition coap_option.h:26
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
void coap_proxy_cleanup(coap_context_t *context)
Close down proxy tracking, releasing any memory used.
void coap_proxy_remove_association(coap_session_t *session, int send_failure)
void coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2578
coap_mid_t coap_send_rst_lkd(coap_session_t *session, const coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition coap_net.c:971
coap_mid_t coap_send_message_type_lkd(coap_session_t *session, const coap_pdu_t *request, coap_pdu_type_t type)
Helper function to create and send a message with type (usually ACK or RST).
Definition coap_net.c:1095
coap_mid_t coap_send_error_lkd(coap_session_t *session, const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Sends an error response with code code for request request to dst.
Definition coap_net.c:1066
void coap_io_do_io_lkd(coap_context_t *ctx, coap_tick_t now)
Processes any outstanding read, write, accept or connect I/O as indicated in the coap_socket_t struct...
Definition coap_net.c:2513
int coap_send_recv_lkd(coap_session_t *session, coap_pdu_t *request_pdu, coap_pdu_t **response_pdu, uint32_t timeout_ms)
Definition coap_net.c:1984
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1763
unsigned int coap_io_prepare_epoll_lkd(coap_context_t *ctx, coap_tick_t now)
Any now timed out delayed packet is transmitted, along with any packets associated with requested obs...
Definition coap_io.c:1260
coap_mid_t coap_send_lkd(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1355
coap_mid_t coap_send_ack_lkd(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition coap_net.c:986
#define COAP_IO_NO_WAIT
Definition coap_net.h:663
#define COAP_IO_WAIT
Definition coap_net.h:662
COAP_API void coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2567
COAP_API void coap_io_do_io(coap_context_t *ctx, coap_tick_t now)
Processes any outstanding read, write, accept or connect I/O as indicated in the coap_socket_t struct...
Definition coap_net.c:2506
int coap_add_data_large_response_lkd(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_string_t *query, uint16_t media_type, int maxage, uint64_t etag, size_t length, const uint8_t *data, coap_release_large_data_t release_func, void *app_ptr)
Associates given data with the response pdu that is passed as fourth parameter.
void coap_block_delete_lg_srcv(coap_session_t *session, coap_lg_srcv_t *lg_srcv)
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
int coap_handle_response_get_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, coap_recurse_t recursive)
void coap_check_code_lg_xmit(const coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_resource_t *resource, const coap_string_t *query)
The function checks that the code in a newly formed lg_xmit created by coap_add_data_large_response_l...
int coap_handle_response_send_block(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
int coap_handle_request_put_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *uri_path, coap_opt_t *observe, int *added_block, coap_lg_srcv_t **free_lg_srcv)
#define STATE_TOKEN_BASE(t)
coap_lg_crcv_t * coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu, coap_lg_xmit_t *lg_xmit)
int coap_handle_request_send_block(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *query)
@ COAP_RECURSE_OK
#define COAP_OPT_BLOCK_SZX(opt)
Returns the value of the SZX-field of a Block option opt.
Definition coap_block.h:90
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:63
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:62
int coap_get_block_b(const coap_session_t *session, const coap_pdu_t *pdu, coap_option_num_t number, coap_block_b_t *block)
Initializes block from pdu.
Definition coap_block.c:62
#define COAP_BLOCK_NO_PREEMPTIVE_RTAG
Definition coap_block.h:65
#define COAP_BLOCK_CACHE_RESPONSE
Definition coap_block.h:69
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:61
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
int coap_digest_final(coap_digest_ctx_t *digest_ctx, coap_digest_t *digest_buffer)
Finalize the coap_digest information into the provided digest_buffer.
int coap_digest_update(coap_digest_ctx_t *digest_ctx, const uint8_t *data, size_t data_len)
Update the coap_digest information with the next chunk of data.
void coap_digest_ctx_t
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
void coap_delete_cache_entry(coap_context_t *context, coap_cache_entry_t *cache_entry)
Remove a cache-entry from the hash list and free off all the appropriate contents apart from app_data...
int64_t coap_tick_diff_t
This data type is used to represent the difference between two clock_tick_t values.
Definition coap_time.h:155
void coap_clock_init(void)
Initializes the internal clock.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:143
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:158
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
void coap_prng_init_lkd(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition coap_prng.c:166
int coap_prng_lkd(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition coap_prng.c:178
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
coap_print_status_t coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, const coap_string_t *query_filter)
Prints the names of all known resources for context to buf.
coap_resource_t * coap_get_resource_from_uri_path_lkd(coap_context_t *context, coap_str_const_t *uri_path)
Returns the resource identified by the unique string uri_path.
#define RESOURCES_ITER(r, tmp)
#define COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
Define this when invoking coap_resource_unknown_init2() if .well-known/core is to be passed to the un...
#define COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT
This resource has support for multicast requests.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX
Disable libcoap library suppressing 4.xx multicast responses (overridden by RFC7969 No-Response optio...
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS
Disable libcoap library from adding in delays to multicast requests before releasing the response bac...
void(* coap_method_handler_t)(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
Definition of message handler function.
#define COAP_RESOURCE_FLAGS_OSCORE_ONLY
Define this resource as an OSCORE enabled access only.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX
Disable libcoap library suppressing 5.xx multicast responses (overridden by RFC7969 No-Response optio...
uint32_t coap_print_status_t
Status word to encode the result of conditional print or copy operations such as coap_print_link().
#define COAP_PRINT_STATUS_ERROR
#define COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY
Force all large traffic to this resource to be presented as a single body to the request handler.
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05
Enable libcoap library suppression of 205 multicast responses that are empty (overridden by RFC7969 N...
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX
Enable libcoap library suppressing 2.xx multicast responses (overridden by RFC7969 No-Response option...
void coap_register_option_lkd(coap_context_t *ctx, uint16_t type)
Registers the option type type with the given context object ctx.
Definition coap_net.c:4871
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4644
uint16_t coap_new_message_id_lkd(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now)
Set sendqueue_basetime in the given context object ctx to now.
Definition coap_net.c:130
int coap_delete_node_lkd(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:227
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition coap_net.c:247
int coap_context_set_psk2_lkd(coap_context_t *context, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node)
This function removes the element with given id from the list given list.
Definition coap_net.c:2728
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition coap_net.c:270
COAP_API int coap_delete_node(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:204
int coap_client_delay_first(coap_session_t *session)
Delay the sending of the first client request until some other negotiation has completed.
Definition coap_net.c:1226
int coap_context_set_psk_lkd(coap_context_t *context, const char *hint, const uint8_t *key, size_t key_len)
Set the context's default PSK hint and/or key for a server.
coap_queue_t * coap_pop_next(coap_context_t *context)
Returns the next pdu to send and removes it from the sendqeue.
Definition coap_net.c:278
void coap_dispatch(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Dispatches the PDUs from the receive queue in given context.
Definition coap_net.c:4131
int coap_insert_node(coap_queue_t **queue, coap_queue_t *node)
Adds node to given queue, ordered by variable t in node.
Definition coap_net.c:167
unsigned int coap_calc_timeout(coap_session_t *session, unsigned char r)
Calculates the initial timeout based on the session CoAP transmission parameters 'ack_timeout',...
Definition coap_net.c:1123
int coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *groupname, const char *ifname)
Function interface for joining a multicast group for listening for the currently defined endpoints th...
void coap_free_context_lkd(coap_context_t *context)
CoAP stack context must be released with coap_free_context_lkd().
Definition coap_net.c:755
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *request_pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1708
int coap_can_exit_lkd(coap_context_t *context)
Returns 1 if there are no messages to send or to dispatch in the context's queues.
Definition coap_net.c:4706
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2099
int coap_check_code_class(coap_session_t *session, coap_pdu_t *pdu)
Check whether the pdu contains a valid code class.
Definition coap_net.c:1293
int coap_context_set_pki_root_cas_lkd(coap_context_t *ctx, const char *ca_file, const char *ca_dir)
Set the context's default Root CA information for a client or server.
Definition coap_net.c:448
int coap_option_check_critical(coap_session_t *session, coap_pdu_t *pdu, coap_opt_filter_t *unknown)
Verifies that pdu contains no unknown critical options.
Definition coap_net.c:846
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1149
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition coap_net.c:256
void coap_cancel_session_messages(coap_context_t *context, coap_session_t *session, coap_nack_reason_t reason)
Cancels all outstanding messages for session session.
Definition coap_net.c:2832
int coap_context_set_pki_lkd(coap_context_t *context, const coap_dtls_pki_t *setup_data)
Set the context's default PKI information for a server.
int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *msg, size_t msg_len)
Parses and interprets a CoAP datagram with context ctx.
Definition coap_net.c:2683
void coap_cancel_all_messages(coap_context_t *context, coap_session_t *session, coap_bin_const_t *token)
Cancels all outstanding messages for session session that have the specified token.
Definition coap_net.c:2871
void coap_context_set_session_timeout(coap_context_t *context, unsigned int session_timeout)
Set the session timeout value.
Definition coap_net.c:546
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:499
COAP_API int coap_join_mcast_group_intf(coap_context_t *ctx, const char *groupname, const char *ifname)
Function interface for joining a multicast group for listening for the currently defined endpoints th...
void(* coap_pong_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Pong handler that is used as callback in coap_context_t.
Definition coap_net.h:100
unsigned int coap_context_get_max_idle_sessions(const coap_context_t *context)
Get the maximum idle sessions count.
Definition coap_net.c:488
COAP_API int coap_send_recv(coap_session_t *session, coap_pdu_t *request_pdu, coap_pdu_t **response_pdu, uint32_t timeout_ms)
Definition coap_net.c:1963
coap_context_t * coap_new_context(const coap_address_t *listen_addr)
Creates a new coap_context_t object that will hold the CoAP stack status.
Definition coap_net.c:642
COAP_API coap_mid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1345
COAP_API int coap_context_set_pki(coap_context_t *context, const coap_dtls_pki_t *setup_data)
Set the context's default PKI information for a server.
void coap_mcast_per_resource(coap_context_t *context)
Function interface to enable processing mcast requests on a per resource basis.
coap_response_t(* coap_response_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_pdu_t *received, const coap_mid_t mid)
Response handler that is used as callback in coap_context_t.
Definition coap_net.h:64
COAP_API coap_mid_t coap_send_error(coap_session_t *session, const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Sends an error response with code code for request request to dst.
Definition coap_net.c:1053
void coap_context_set_csm_max_message_size(coap_context_t *context, uint32_t csm_max_message_size)
Set the CSM max session size value.
Definition coap_net.c:534
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition coap_net.c:506
void coap_send_recv_terminate(void)
Terminate any active coap_send_recv() sessions.
Definition coap_net.c:1958
void coap_register_response_handler(coap_context_t *context, coap_response_handler_t handler)
Registers a new message handler that is called whenever a response is received.
Definition coap_net.c:4835
coap_pdu_t * coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Creates a new ACK PDU with specified error code.
Definition coap_net.c:2904
void coap_context_set_max_handshake_sessions(coap_context_t *context, unsigned int max_handshake_sessions)
Set the maximum number of sessions in (D)TLS handshake value.
Definition coap_net.c:493
int coap_context_get_coap_fd(const coap_context_t *context)
Get the libcoap internal file descriptor for using in an application's select() or returned as an eve...
Definition coap_net.c:557
int coap_mcast_set_hops(coap_session_t *session, size_t hops)
Function interface for defining the hop count (ttl) for sending multicast traffic.
void coap_context_set_app_data(coap_context_t *context, void *app_data)
Stores data with the given context.
Definition coap_net.c:630
coap_response_t
Definition coap_net.h:48
void(* coap_ping_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Ping handler that is used as callback in coap_context_t.
Definition coap_net.h:89
void coap_ticks(coap_tick_t *)
Returns the current value of an internal tick counter.
COAP_API void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition coap_net.c:746
void(* coap_nack_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
Negative Acknowedge handler that is used as callback in coap_context_t.
Definition coap_net.h:77
void * coap_context_get_app_data(const coap_context_t *context)
Returns any application-specific data that has been stored with context using the function coap_conte...
Definition coap_net.c:636
COAP_API int coap_context_set_pki_root_cas(coap_context_t *ctx, const char *ca_file, const char *ca_dir)
Set the context's default Root CA information for a client or server.
Definition coap_net.c:436
uint32_t coap_context_get_csm_max_message_size(const coap_context_t *context)
Get the CSM max session size value.
Definition coap_net.c:541
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:552
COAP_API int coap_context_set_psk(coap_context_t *context, const char *hint, const uint8_t *key, size_t key_len)
Set the context's default PSK hint and/or key for a server.
COAP_API void coap_register_option(coap_context_t *ctx, uint16_t type)
Registers the option type type with the given context object ctx.
Definition coap_net.c:4864
COAP_API coap_mid_t coap_send_ack(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition coap_net.c:976
unsigned int coap_context_get_csm_timeout_ms(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:529
void coap_register_ping_handler(coap_context_t *context, coap_ping_handler_t handler)
Registers a new message handler that is called whenever a CoAP Ping message is received.
Definition coap_net.c:4852
COAP_API int coap_context_set_psk2(coap_context_t *context, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
int coap_context_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
Definition coap_net.c:463
void * coap_get_app_data(const coap_context_t *ctx)
Definition coap_net.c:740
void coap_context_set_max_idle_sessions(coap_context_t *context, unsigned int max_idle_sessions)
Set the maximum idle sessions count.
Definition coap_net.c:482
COAP_API coap_mid_t coap_send_message_type(coap_session_t *session, const coap_pdu_t *request, coap_pdu_type_t type)
Helper function to create and send a message with type (usually ACK or RST).
Definition coap_net.c:1084
COAP_API coap_mid_t coap_send_rst(coap_session_t *session, const coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition coap_net.c:961
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition coap_net.c:458
void coap_set_app_data(coap_context_t *ctx, void *app_data)
Definition coap_net.c:734
COAP_API int coap_can_exit(coap_context_t *context)
Returns 1 if there are no messages to send or to dispatch in the context's queues.
Definition coap_net.c:4696
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:513
void coap_register_pong_handler(coap_context_t *context, coap_pong_handler_t handler)
Registers a new message handler that is called whenever a CoAP Pong message is received.
Definition coap_net.c:4858
void coap_context_set_max_token_size(coap_context_t *context, size_t max_token_size)
Set the maximum token size (RFC8974).
Definition coap_net.c:474
COAP_API int coap_handle_event(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4633
void coap_register_nack_handler(coap_context_t *context, coap_nack_handler_t handler)
Registers a new message handler that is called whenever a confirmable message (request or response) i...
Definition coap_net.c:4846
void coap_context_set_csm_timeout_ms(coap_context_t *context, unsigned int csm_timeout_ms)
Set the CSM timeout value.
Definition coap_net.c:519
@ COAP_RESPONSE_FAIL
Response not liked - send CoAP RST packet.
Definition coap_net.h:49
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:50
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *coap_session)
Get the current client's PSK identity.
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition coap_notls.c:149
coap_session_t * coap_session_new_dtls_session(coap_session_t *session, coap_tick_t now)
Create a new DTLS session for the session.
int coap_dtls_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
int coap_dtls_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
int coap_dtls_context_set_spsk(coap_context_t *coap_context, coap_dtls_spsk_t *setup_data)
Set the DTLS context's default server PSK information.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:161
const coap_bin_const_t * coap_get_session_client_psk_key(const coap_session_t *coap_session)
Get the current client's PSK key.
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
const coap_bin_const_t * coap_get_session_server_psk_hint(const coap_session_t *coap_session)
Get the current server's PSK identity hint.
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition coap_dtls.h:307
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:46
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:47
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:38
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:67
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:77
coap_event_t
Scalar type to represent different events, e.g.
Definition coap_event.h:34
@ COAP_EVENT_OSCORE_DECODE_ERROR
Triggered when there is an OSCORE decode of OSCORE option failure.
Definition coap_event.h:118
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:61
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:116
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:39
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:55
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h:125
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:41
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:71
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:73
@ COAP_EVENT_SERVER_SESSION_NEW
Called in the CoAP IO loop if a new server-side session is created due to an incoming connection.
Definition coap_event.h:85
@ COAP_EVENT_OSCORE_NOT_ENABLED
Triggered when trying to use OSCORE to decrypt, but it is not enabled.
Definition coap_event.h:110
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:127
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:63
@ COAP_EVENT_SERVER_SESSION_DEL
Called in the CoAP IO loop if a server session is deleted (e.g., due to inactivity or because the max...
Definition coap_event.h:94
@ COAP_EVENT_OSCORE_NO_SECURITY
Triggered when there is no OSCORE security definition found.
Definition coap_event.h:114
@ COAP_EVENT_DTLS_RENEGOTIATE
Triggered when (D)TLS session renegotiated.
Definition coap_event.h:43
@ COAP_EVENT_BAD_PACKET
Triggered when badly formatted packet received.
Definition coap_event.h:100
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:102
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:112
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:53
@ COAP_EVENT_WS_PACKET_SIZE
Triggered when there is an oversize WebSockets packet.
Definition coap_event.h:123
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:51
@ COAP_EVENT_OSCORE_DECRYPTION_FAILURE
Triggered when there is an OSCORE decryption failure.
Definition coap_event.h:108
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:132
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:45
coap_mutex_t coap_lock_t
#define coap_lock_callback_ret_release(r, c, func, failed)
Dummy for no thread-safe code.
#define coap_lock_callback_release(c, func, failed)
Dummy for no thread-safe code.
#define coap_lock_unlock(c)
Dummy for no thread-safe code.
#define coap_lock_lock(c, failed)
Dummy for no thread-safe code.
#define coap_lock_callback(c, func)
Dummy for no thread-safe code.
#define coap_lock_check_locked(c)
Dummy for no thread-safe code.
#define coap_lock_init()
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, c, func)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition coap_debug.c:101
#define coap_log_alert(...)
Definition coap_debug.h:84
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:784
#define coap_log_emerg(...)
Definition coap_debug.h:81
size_t coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition coap_debug.c:239
const char * coap_endpoint_str(const coap_endpoint_t *endpoint)
Get endpoint description.
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
@ COAP_LOG_DEBUG
Definition coap_debug.h:58
@ COAP_LOG_WARN
Definition coap_debug.h:55
int coap_netif_strm_connect2(coap_session_t *session)
Layer function interface for Netif stream connect (tcp).
ssize_t coap_netif_dgrm_read(coap_session_t *session, coap_packet_t *packet)
Function interface for layer data datagram receiving for sessions.
Definition coap_netif.c:72
ssize_t coap_netif_dgrm_read_ep(coap_endpoint_t *endpoint, coap_packet_t *packet)
Function interface for layer data datagram receiving for endpoints.
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
#define COAP_OBSERVE_CANCEL
The value COAP_OBSERVE_CANCEL in a GET/FETCH request option COAP_OPTION_OBSERVE indicates that the ob...
#define COAP_OBSERVE_ESTABLISH
The value COAP_OBSERVE_ESTABLISH in a GET/FETCH request option COAP_OPTION_OBSERVE indicates a new ob...
coap_opt_t * coap_option_next(coap_opt_iterator_t *oi)
Updates the iterator oi to point to the next option.
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
coap_opt_iterator_t * coap_option_iterator_init(const coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t *filter)
Initializes the given option iterator oi to point to the beginning of the pdu's option list.
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
int coap_option_filter_unset(coap_opt_filter_t *filter, coap_option_num_t option)
Clears the corresponding entry for number in filter.
void coap_option_filter_clear(coap_opt_filter_t *filter)
Clears filter filter.
coap_opt_t * coap_check_option(const coap_pdu_t *pdu, coap_option_num_t number, coap_opt_iterator_t *oi)
Retrieves the first option of number number from pdu.
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
int coap_option_filter_get(coap_opt_filter_t *filter, coap_option_num_t option)
Checks if number is contained in filter.
int coap_option_filter_set(coap_opt_filter_t *filter, coap_option_num_t option)
Sets the corresponding entry for number in filter.
coap_pdu_t * coap_oscore_new_pdu_encrypted_lkd(coap_session_t *session, coap_pdu_t *pdu, coap_bin_const_t *kid_context, oscore_partial_iv_t send_partial_iv)
Encrypts the specified pdu when OSCORE encryption is required on session.
struct coap_pdu_t * coap_oscore_decrypt_pdu(coap_session_t *session, coap_pdu_t *pdu)
Decrypts the OSCORE-encrypted parts of pdu when OSCORE is used.
int coap_rebuild_pdu_for_proxy(coap_pdu_t *pdu)
Convert PDU to use Proxy-Scheme option if Proxy-Uri option is present.
void coap_delete_all_oscore(coap_context_t *context)
Cleanup all allocated OSCORE information.
#define COAP_PDU_IS_RESPONSE(pdu)
coap_pdu_t * coap_pdu_reference_lkd(coap_pdu_t *pdu)
Increment reference counter on a pdu to stop it prematurely getting freed off when coap_delete_pdu() ...
Definition coap_pdu.c:1623
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:190
#define COAP_TOKEN_EXT_2B_TKL
size_t coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Inserts option of given number in the pdu with the appropriate data.
Definition coap_pdu.c:626
int coap_remove_option(coap_pdu_t *pdu, coap_option_num_t number)
Removes (first) option of given number from the pdu.
Definition coap_pdu.c:489
#define COAP_DROPPED_RESPONSE
Indicates that a response is suppressed.
int coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto)
Decode the protocol specific header for the specified PDU.
Definition coap_pdu.c:1073
size_t coap_pdu_parse_header_size(coap_proto_t proto, const uint8_t *data)
Interprets data to determine the number of bytes in the header.
Definition coap_pdu.c:989
#define COAP_PDU_DELAYED
#define COAP_PDU_IS_EMPTY(pdu)
#define COAP_PDU_IS_SIGNALING(pdu)
int coap_option_check_repeatable(coap_option_num_t number)
Check whether the option is allowed to be repeated or not.
Definition coap_pdu.c:583
int coap_pdu_parse_opt(coap_pdu_t *pdu)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition coap_pdu.c:1335
size_t coap_update_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Updates existing first option of given number in the pdu with the new data.
Definition coap_pdu.c:720
#define COAP_TOKEN_EXT_1B_TKL
size_t coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto)
Compose the protocol specific header for the specified PDU.
Definition coap_pdu.c:1485
#define COAP_DEFAULT_VERSION
size_t coap_pdu_parse_size(coap_proto_t proto, const uint8_t *data, size_t length)
Parses data to extract the message size.
Definition coap_pdu.c:1020
int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size)
Dynamically grows the size of pdu to new_size.
Definition coap_pdu.c:297
#define COAP_PDU_IS_REQUEST(pdu)
size_t coap_add_option_internal(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition coap_pdu.c:776
#define COAP_OPTION_HOP_LIMIT
Definition coap_pdu.h:133
#define COAP_OPTION_NORESPONSE
Definition coap_pdu.h:145
#define COAP_OPTION_URI_HOST
Definition coap_pdu.h:120
#define COAP_OPTION_IF_MATCH
Definition coap_pdu.h:119
#define COAP_OPTION_BLOCK2
Definition coap_pdu.h:137
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:947
#define COAP_OPTION_CONTENT_FORMAT
Definition coap_pdu.h:128
#define COAP_OPTION_BLOCK1
Definition coap_pdu.h:138
#define COAP_OPTION_Q_BLOCK1
Definition coap_pdu.h:135
#define COAP_OPTION_PROXY_SCHEME
Definition coap_pdu.h:142
#define COAP_OPTION_URI_QUERY
Definition coap_pdu.h:132
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:263
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:56
#define COAP_OPTION_IF_NONE_MATCH
Definition coap_pdu.h:122
#define COAP_TOKEN_EXT_MAX
Definition coap_pdu.h:60
#define COAP_OPTION_URI_PATH
Definition coap_pdu.h:127
#define COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH
Definition coap_pdu.h:199
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:160
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:163
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:326
#define COAP_OPTION_OSCORE
Definition coap_pdu.h:126
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:68
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition coap_pdu.h:198
int coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds token of length len to pdu.
Definition coap_pdu.c:356
#define COAP_OPTION_Q_BLOCK2
Definition coap_pdu.h:140
#define COAP_SIGNALING_OPTION_CUSTODY
Definition coap_pdu.h:202
int coap_pdu_parse(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1462
#define COAP_OPTION_RTAG
Definition coap_pdu.h:146
#define COAP_OPTION_URI_PORT
Definition coap_pdu.h:124
coap_pdu_t * coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition coap_pdu.c:99
#define COAP_OPTION_ACCEPT
Definition coap_pdu.h:134
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:266
#define COAP_OPTION_PROXY_URI
Definition coap_pdu.h:141
#define COAP_OPTION_OBSERVE
Definition coap_pdu.h:123
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:53
#define COAP_BERT_BASE
Definition coap_pdu.h:44
#define COAP_OPTION_ECHO
Definition coap_pdu.h:144
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:214
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:197
int coap_add_data(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds given data to the pdu that is passed as first parameter.
Definition coap_pdu.c:841
@ COAP_REQUEST_GET
Definition coap_pdu.h:79
@ COAP_PROTO_WS
Definition coap_pdu.h:318
@ COAP_PROTO_DTLS
Definition coap_pdu.h:315
@ COAP_PROTO_UDP
Definition coap_pdu.h:314
@ COAP_PROTO_WSS
Definition coap_pdu.h:319
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:369
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:365
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:366
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:332
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:367
@ COAP_EMPTY_CODE
Definition coap_pdu.h:327
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:329
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:368
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:333
@ COAP_MESSAGE_NON
Definition coap_pdu.h:70
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:71
@ COAP_MESSAGE_CON
Definition coap_pdu.h:69
@ COAP_MESSAGE_RST
Definition coap_pdu.h:72
void coap_connect_session(coap_session_t *session, coap_tick_t now)
ssize_t coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
#define COAP_DEFAULT_LEISURE_TICKS(s)
The DEFAULT_LEISURE definition for the session (s).
void coap_handle_nack(coap_session_t *session, coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
size_t coap_session_max_pdu_rcv_size(const coap_session_t *session)
Get maximum acceptable receive PDU size.
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Lookup the server session for the packet received on an endpoint, or create a new one.
void coap_free_endpoint_lkd(coap_endpoint_t *endpoint)
Release an endpoint and all the structures associated with it.
void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2277
void coap_session_server_keepalive_failed(coap_session_t *session)
Clear down a session following a keepalive failure.
#define COAP_NSTART(s)
#define COAP_MAX_PAYLOADS(s)
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
ssize_t coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu)
Send a pdu according to the session's protocol.
Definition coap_net.c:1001
size_t coap_session_max_pdu_size_lkd(const coap_session_t *session)
Get maximum acceptable PDU size.
void coap_session_release_lkd(coap_session_t *session)
Decrement reference counter on a session.
coap_session_t * coap_session_reference_lkd(coap_session_t *session)
Increment reference counter on a session.
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
coap_endpoint_t * coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto)
Create a new endpoint for communicating with peers.
coap_session_t * coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep, void *extra)
Creates a new server session for the specified endpoint.
@ COAP_EXT_T_NOT_CHECKED
Not checked.
@ COAP_EXT_T_CHECKING
Token size check request sent.
@ COAP_EXT_T_CHECKED
Token size valid.
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
coap_session_state_t
coap_session_state_t values
#define COAP_PROTO_NOT_RELIABLE(p)
#define COAP_PROTO_RELIABLE(p)
@ COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
@ COAP_SESSION_TYPE_CLIENT
client-side
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_NONE
void coap_delete_bin_const(coap_bin_const_t *s)
Deletes the given const binary data and releases any memory allocated.
Definition coap_str.c:120
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:110
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:211
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:197
coap_string_t * coap_new_string(size_t size)
Returns a new string object with at least size+1 bytes storage allocated.
Definition coap_str.c:21
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:46
int coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, coap_pdu_t *request)
Removes any subscription for session observer from resource and releases the allocated storage.
void coap_persist_cleanup(coap_context_t *context)
Close down persist tracking, releasing any memory used.
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Removes any subscription for session observer from resource and releases the allocated storage.
int coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Handles a failed observe notify.
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, const coap_pdu_t *pdu)
Adds the specified peer as observer for resource.
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Flags that data is ready to be sent to observers.
int coap_epoll_is_supported(void)
Determine whether epoll is supported or not.
Definition coap_net.c:567
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_af_unix_is_supported(void)
Check whether socket type AF_UNIX is available.
Definition coap_net.c:621
int coap_ipv6_is_supported(void)
Check whether IPv6 is available.
Definition coap_net.c:594
int coap_threadsafe_is_supported(void)
Determine whether libcoap is threadsafe or not.
Definition coap_net.c:576
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_server_is_supported(void)
Check whether Server code is available.
Definition coap_net.c:612
int coap_client_is_supported(void)
Check whether Client code is available.
Definition coap_net.c:603
int coap_ipv4_is_supported(void)
Check whether IPv4 is available.
Definition coap_net.c:585
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:990
int coap_split_proxy_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri)
Parses a given string into URI components.
Definition coap_uri.c:281
coap_string_t * coap_get_query(const coap_pdu_t *request)
Extract query string from request PDU according to escape rules in 6.5.8.
Definition coap_uri.c:939
#define COAP_UNUSED
Definition libcoap.h:70
#define COAP_STATIC_INLINE
Definition libcoap.h:53
coap_address_t remote
remote address and port
Definition coap_io.h:56
coap_address_t local
local address and port
Definition coap_io.h:57
Multi-purpose address abstraction.
struct sockaddr_in sin
union coap_address_t::@375231102122066221014365114153252245033016366266 addr
struct sockaddr_in6 sin6
struct sockaddr sa
CoAP binary data definition with const data.
Definition coap_str.h:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
CoAP binary data definition.
Definition coap_str.h:56
size_t length
length of binary data
Definition coap_str.h:57
uint8_t * s
binary data
Definition coap_str.h:58
Structure of Block options with BERT support.
Definition coap_block.h:51
unsigned int num
block number
Definition coap_block.h:52
unsigned int bert
Operating as BERT.
Definition coap_block.h:57
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:55
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:53
unsigned int szx
block size (0-6)
Definition coap_block.h:54
The CoAP stack's global state is stored in a coap_context_t object.
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
coap_pong_handler_t pong_handler
Called when a ping response is received.
void * app
application-specific data
coap_session_t * sessions
client sessions
coap_nack_handler_t nack_handler
Called when a response issue has occurred.
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
coap_resource_t * resources
hash table or list of known resources
uint16_t * cache_ignore_options
CoAP options to ignore when creating a cache-key.
coap_opt_filter_t known_options
coap_ping_handler_t ping_handler
Called when a CoAP ping is received.
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
size_t cache_ignore_count
The number of CoAP options to ignore when creating a cache-key.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
coap_response_handler_t response_handler
Called when a response is received.
coap_cache_entry_t * cache
CoAP cache-entry cache.
uint8_t mcast_per_resource
Mcast controlled on a per resource basis.
coap_endpoint_t * endpoint
the endpoints used for listening
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
coap_event_handler_t handle_event
Callback function that is used to signal events to the application.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
coap_resource_t * unknown_resource
can be used for handling unknown resources
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:381
coap_bin_const_t identity
Definition coap_dtls.h:380
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:443
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:312
uint8_t version
Definition coap_dtls.h:313
coap_bin_const_t hint
Definition coap_dtls.h:451
coap_bin_const_t key
Definition coap_dtls.h:452
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:501
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:533
Abstraction of virtual endpoint that can be attached to coap_context_t.
coap_context_t * context
endpoint's context
coap_session_t * sessions
hash table or list of active sessions
coap_address_t bind_addr
local interface address
coap_socket_t sock
socket object for the interface, if any
coap_proto_t proto
protocol used on this interface
uint64_t state_token
state token
coap_binary_t * app_token
original PDU token
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
Structure to hold large body (many blocks) client receive information.
uint64_t state_token
state token
coap_binary_t * app_token
app requesting PDU token
Structure to hold large body (many blocks) server receive information.
Structure to hold large body (many blocks) transmission information.
union coap_lg_xmit_t::@346173123032116353302231052050034003045167377246 b
coap_pdu_t pdu
skeletal PDU
coap_l_block1_t b1
uint16_t option
large block transmisson CoAP option
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
coap_lg_xmit_t * lg_xmit
Holds ptr to lg_xmit if sending a set of blocks.
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
uint8_t hdr_size
actual size used for protocol-specific header (0 until header is encoded)
coap_bin_const_t actual_token
Actual token in pdu.
uint8_t * data
first byte of payload, if any
coap_mid_t mid
message id, if any, in regular host byte order
uint32_t e_token_length
length of Token space (includes leading extended bytes
size_t used_size
used bytes of storage for token, options and payload
uint8_t crit_opt
Set if unknown critical option for proxy.
size_t alloc_size
allocated storage for token, options and payload
coap_session_t * session
Session responsible for PDU or NULL.
coap_pdu_type_t type
message type
Queue entry.
coap_session_t * session
the CoAP session
coap_pdu_t * pdu
the CoAP PDU to send
unsigned int timeout
the randomized timeout value
uint8_t is_mcast
Set if this is a queued mcast response.
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Abstraction of resource that can be attached to coap_context_t.
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
coap_str_const_t * uri_path
Request URI Path for this resource.
unsigned int observe
The next value for the Observe option.
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
unsigned int is_proxy_uri
resource created for proxy URI handler
unsigned int is_unknown
resource created for unknown handler
unsigned int is_reverse_proxy
resource created for reverse proxy URI handler
unsigned int observable
can be observed
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
int flags
zero or more COAP_RESOURCE_FLAGS_* or'd together
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
unsigned ref_subscriptions
reference count of current subscriptions
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint8_t doing_first
Set if doing client's first request.
uint8_t delay_recursive
Set if in coap_client_delay_first()
coap_socket_t sock
socket object for the session, if any
coap_pdu_t * partial_pdu
incomplete incoming pdu
uint32_t max_token_size
Largest token size supported RFC8974.
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
coap_session_state_t state
current state of relationship with peer
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote)
coap_digest_t cached_pdu_cksum
Checksum of last CON request PDU.
coap_mid_t remote_test_mid
mid used for checking remote support
uint8_t read_header[8]
storage space for header of incoming message header
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
unsigned ref
reference count from queues
coap_response_t last_con_handler_res
The result of calling the response handler of the last CON.
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
uint8_t doing_send_recv
Set if coap_send_recv() active.
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
uint8_t csm_block_supported
CSM TCP blocks supported.
uint8_t proxy_session
Set if this is an ongoing proxy session.
uint8_t con_active
Active CON request sent.
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
uint32_t tx_rtag
Next Request-Tag number to use.
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
coap_lg_srcv_t * lg_srcv
Server list of expected large receives.
coap_bin_const_t * req_token
Token in request pdu of coap_send_recv()
coap_pdu_t * resp_pdu
PDU returned in coap_send_recv() call.
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
coap_mid_t last_con_mid
The last CON mid that has been been processed.
coap_session_type_t type
client or server side socket
coap_mid_t last_ack_mid
The last ACK mid that has been been processed.
coap_context_t * context
session's context
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
coap_pdu_t * cached_pdu
Cached copy of last ACK response PDU.
coap_bin_const_t * echo
last token used to make a request
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
coap_session_t * session
Used to determine session owner.
coap_endpoint_t * endpoint
Used by the epoll logic for a listening endpoint.
coap_address_t mcast_addr
remote address and port (multicast track)
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
CoAP string data definition with const data.
Definition coap_str.h:46
const uint8_t * s
read-only string data
Definition coap_str.h:48
size_t length
length of string
Definition coap_str.h:47
CoAP string data definition.
Definition coap_str.h:38
uint8_t * s
string data
Definition coap_str.h:40
size_t length
length of string
Definition coap_str.h:39
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
struct coap_session_t * session
subscriber session
coap_pdu_t * pdu
cache_key to identify requester
Representation of parsed URI.
Definition coap_uri.h:68
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:69